package com.scfire.manage

import grails.converters.JSON
import grails.transaction.Transactional

import java.text.DateFormat
import java.text.DecimalFormat
import java.text.SimpleDateFormat

import net.sf.json.JSONArray
import net.sf.json.JSONObject

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.transaction.annotation.Propagation

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBCursor
import com.mongodb.DBObject
import com.paic.qhcs.util.*
import com.paic.qhcs.util.entry.ResultEntry
import com.scfire.baseInfo.Gson
import com.scfire.bean.DonateDetailReport
import com.scfire.bean.DonateReport
import com.scfire.bean.FundPoolDetailReport
import com.scfire.bean.ProjectFeeDetailReport
import com.scfire.bean.UserInfoReport
import com.scfire.cert.CreditRank
import com.scfire.content.*
import com.scfire.festival.*
import com.scfire.fund.FDonate
import com.scfire.fund.FOperate
import com.scfire.fund.FRuler
import com.scfire.fund.FundPool
import com.scfire.message.InterfaceMesage
import com.scfire.message.SystemMessage
import com.scfire.project.Banner
import com.scfire.project.Comment
import com.scfire.project.Donate
import com.scfire.project.Fundraise
import com.scfire.project.Home
import com.scfire.project.MainCate
import com.scfire.project.Payment
import com.scfire.project.Project
import com.scfire.project.ProjectClosing
import com.scfire.project.ProjectFeedback
import com.scfire.project.SubProject
import com.scfire.security.Member
import com.scfire.util.*
import com.scfire.weixin.AutoReply
import com.scfire.weixin.MainMenu
import com.scfire.weixin.SubMenu
import com.scfire.weixin.WeiXinConstants

class ManageController {
	
	Log LOG = LogFactory.getLog(ManageController.class)
	
	def springSecurityService
	def deviceInfoService
	def weiXinService
	def mongo
	def exportService
	def SystemMessageService
	def feedBackService
	def grailsApplication
	def DonateMoney(){
		Long x = new Date().getTime();
		println "---------开始处理时间: " + new Date()+ "---------"
		FileWriter   fw=new   FileWriter(new File("D:/tocheck/order2.txt"));
		BufferedWriter   bw=new   BufferedWriter(fw);
		String lineTxt = null;
		def donates= Donate.list();
		int i=0
		for(Donate d:donates){
			i++
			println i
			if(d?.operate_fee_status==false){
				if(d.money==d.donate_fee){
					
					println d.id+"------"+d?.operate_fee_status+"-------"+d.money+"--------"+i
				}else{
				bw.write(d.id+"~"+d?.operate_fee_status+"~"+d.money+"~"+d?.donate_fee+"~"+d?.operate_fee);
				bw.newLine();
				bw.flush();
				}
			}else if(d?.operate_fee_status==true){
				if(d.money==(d.donate_fee+d.operate_fee)){
					println d.id+"-------"+d?.operate_fee_status+"------"+d.money+"--------"+i
				}else{
				bw.write(d.id+"~"+d?.operate_fee_status+"~"+d.money+"~"+d?.donate_fee+"~"+d?.operate_fee);
				bw.newLine();
				bw.flush();
				}
			}
		}
		bw.close();
		fw.close();
		println "---------结束处理时间: " + (new Date().getTime()-x)/1000+ "---------"
	}
	
	
	def checkDonateMoney(){
		def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
		DBCollection projectCollection = db.getCollection("donate")
		Long x = new Date().getTime();
		try {
			int i=0;
			println "---------开始处理时间: " + new Date()+ "---------"
			String filePath=params.filePath
			File file=new File(filePath);
			if(file.isFile() && file.exists()){ //判断文件是否存在
				InputStreamReader read = new InputStreamReader(
				new FileInputStream(file));//考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				
				String lineTxt = null;
				
				while((lineTxt = bufferedReader.readLine()) != null){
					//System.out.println(lineTxt);
					String[] s = lineTxt.trim().split("~");
					i++;
					
					if(s[1].trim()=="true"){
						BigDecimal money = new BigDecimal(s[2].trim())
						BigDecimal donate_fee = new BigDecimal(s[3].trim())
						BigDecimal operate_fee = new BigDecimal(s[4].trim())
						BigDecimal total = donate_fee.add(operate_fee)
						if(total.doubleValue()==money.doubleValue()){
							println i+"true"
						}else{
						println i+"false"
						DBObject queryCondition= new BasicDBObject()
						queryCondition.put("_id",Integer.valueOf(s[0].trim()))
						BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("money", total+"")
							.append("donate_fee", s[3].trim())
							.append("operate_fee", s[4].trim())
							)
						
					  projectCollection.update(queryCondition, updateParameter,true,true)
						}
					}else if(s[1].trim()=="false"){
					BigDecimal money = new BigDecimal(s[2].trim())
					BigDecimal donate_fee = new BigDecimal(s[3].trim())
					
					if(donate_fee.doubleValue()==money.doubleValue()){
						println i+"true"
					}else{
					println i+"false"
						DBObject queryCondition1= new BasicDBObject()
						queryCondition1.put("_id",Integer.valueOf(s[0].trim()))
						BasicDBObject updateParameter1 =new BasicDBObject().append("\$set",new BasicDBObject().append("money",s[3].trim())
							.append("donate_fee", s[3].trim())
							)
						projectCollection.update(queryCondition1, updateParameter1,true,true)
						}
					}
				}
				read.close();
	}else{
		System.out.println("找不到指定的文件");
	}
	} catch (Exception e) {
		System.out.println("读取文件内容出错");
		e.printStackTrace();
	}
		
	println "---------结束处理时间: " + (new Date().getTime()-x)/1000+ "---------"
	}
	
	
	
	
	
	
	
	

	def ProjectTotalDonate(){
		def Projects = Project.list();
		int i=0;
		for(Project p:Projects){
			i++
			def donates =p.donates
			def subProjects =p.subProjects
			def fdonates =p.fdonates
			float f
			if(donates){
				p.donateNum= donates.size()
				
				for(Donate d:donates){
					f+=d.donate_fee
					
					
				}
			}else{
			p.donateNum= 0
			}
			if(subProjects){
				p.sbuProjectSize= subProjects.size()
				
			}else{
			p.sbuProjectSize= 0
			}
			if(fdonates){
				p.fDonateSize= fdonates.size()
				for(FDonate d1:fdonates){
					f+=(d1.donate_fee*1.0/100)
				}
			}else{
			p.fDonateSize= 0
			}
			p.realAmount= f
			println i
			p.save flush:true
		}	
	}

	/**
	 * 首页项目推送后台管理
	 * @param project id
	 * @return null
	 *
	 * **/
	def index(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		Member member = (Member) user
		params.max = 10
		
		List<Project> projects = null
		List<Home> homes = null
		int totalCount = 0
		def DTCreate = Project.createCriteria()
		def filterClosure = {
			or{
				eq("verified",SCFIREConstants.PROJECT_APPROVE_PASS)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_EXECUTE)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_EXPIRED)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_OVER)
				eq("verified","doing")
			}
		}
		
		try{
			projects = DTCreate.list(params,filterClosure)
			totalCount = DTCreate.count(filterClosure)
			homes = Home.list()
		}catch(Exception e){
			LOG.error("Project Management info catch exception. "+e.getMessage())
		}
		
		render view: "index", model: [projects:projects,user:member,roles:roles,homes:homes,totalCount:totalCount]
	}
	
	/**
	 * 首页海报管理
	 * @param project id
	 * @return null
	 *
	 * **/
	def banner(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		Banner banner
		try{
			banner = Banner.first()
		}catch(Exception e){
			LOG.error("Project Management info catch exception. "+e.getMessage())
		}
		
		render view: "banner", model: [user:user,roles:roles,banner:banner]
	}
	
	/**
	 * 首页海报保存
	 * @param project id
	 * @return null
	 *
	 * **/
	def bannerSave(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		
		try{
			String img1 = null
			String img2 = null
			String img3 = null
			String img4 = null
			String img5 = null
			String link1=null
			String link2=null
			String link3=null
			String link4=null
			String link5=null
			
						
			if(params.img1!=null){
				img1 = imgSave(params.img1)
				
			}
			if(params.link1!=null){
				link1 = params.link1
				println link1
			}
			if(params.img2!=null){
				img2 = imgSave(params.img2)
			}
			if(params.link2!=null){
				link2 = params.link2
			}
			if(params.img3!=null){
				img3 = imgSave(params.img3)
			}
			if(params.link3!=null){
				link3 = params.link3
			}
			if(params.img4!=null){
				img4 = imgSave(params.img4)
			}
			if(params.link4!=null){
				link4 = params.link4
			}
			if(params.img5!=null){
				img5 = imgSave(params.img5)
			}
			if(params.link5!=null){
				link5 = params.link5
			}
			//只保存一条记录			
			Banner banner = Banner.first()
			if(banner!=null){
				banner.img1 = (img1==null? banner.img1:img1)
				banner.img2 = (img2==null? banner.img2:img2)
				banner.img3 = (img3==null? banner.img3:img3)
				banner.img4 = (img4==null? banner.img4:img4)
				banner.img5 = (img5==null? banner.img5:img5)
				banner.link1 = (link1==null? banner.link1:link1)
				banner.link2 = (link2==null? banner.link2:link2)
				banner.link3 = (link3==null? banner.link3:link3)
				banner.link4 = (link4==null? banner.link4:link4)
				banner.link5 = (link5==null? banner.link5:link5)
				banner.date = new Date()
				banner.save flush:true
			}else{
				banner = new Banner()
				banner.img1 = img1
				banner.img2 = img2
				banner.img3 = img3
				banner.img4 = img4
				banner.img5 = img5
				banner.link1 = link1
				banner.link2 = link2
				banner.link3 = link3
				banner.link4 = link4
				banner.link5 = link5
				banner.date = new Date()
				banner.save flush:true
			}
			
			
		}catch(Exception e){
			LOG.error("Save banner catch exception. "+e.getMessage())
		}
		
		redirect(action:"banner")
	}
	
	/**
	 * 项目推送至首页
	 * @param project id
	 * @return null
	 *
	 * **/
	@Transactional
	def pushHome() {
		def gson = new Gson()
		
		if (params.pid == null || params.position == null || params.status == null) {
			notFound()
			return
		}
		
		def status = params.status
		def position = params.position
		def projectInstance = Project.findById(params.pid)
		//更新home
		def homepageItem = Home.findByProject(projectInstance)
		
		if(homepageItem){
			if(params.status.equals("0")){
				//移除
				homepageItem.delete flush:true
				//保存系统通知消息
				SystemMessage systemMessage = new SystemMessage()
				systemMessage.message = SCFIREConstants.SYSTEM_MESSAGE_PROJECT_CANCLE_PUSH_HOME_FRONT+projectInstance.name+SCFIREConstants.SYSTEM_MESSAGE_PROJECT_CANCLE_PUSH_HOME__BACK
				systemMessage.date = new Date()
				systemMessage.member = projectInstance.member
				systemMessage.save flush:true
				
				redirect  (controller: "manage", action: "index")
				return
			}
			else if (params.status.equals("1")){
				//新增& 修改
				homepageItem.position = Integer.parseInt(position)
			}
			else{
				notFound()
				return
			}
		}
		else{
			homepageItem = new Home();
			homepageItem.project = projectInstance
			homepageItem.position = Integer.parseInt(position)
		}
		
		//更新项目信息
		homepageItem.save (flush:true)
		
		//保存系统通知消息
		SystemMessage systemMessage = new SystemMessage()
		systemMessage.message = SCFIREConstants.SYSTEM_MESSAGE_PROJECT_PUSH_HOME_FRONT+projectInstance.name+SCFIREConstants.SYSTEM_MESSAGE_PROJECT_PUSH_HOME__BACK
		systemMessage.date = new Date()
		systemMessage.member = projectInstance.member
		systemMessage.save flush:true
		
		redirect  (action: "index")
	}
	
	/**
	 * 项目审批
	 * @param project id
	 * @return null
	 *
	 * **/
	def projectApprove(){		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//审批项目
		String projectid = params.projectid
		String opt = params.opt	
		Member member = (Member)user
		Date  date = new Date();
		DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		def project = null
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			def projectMember = Member.findById(project.member)
			
			//项目审批通过
			if(opt==SCFIREConstants.PROJECT_APPROVE_PASS){
				//初次审核通过,进行日期更新
				if(project.approveStatus != null && (!project.approveStatus.equals("true"))){
					project.startDate = new Date()
					Calendar st = new GregorianCalendar()
					st.setTime(project.startDate)
					Calendar et = new GregorianCalendar()
					et.setTime(project.endDate)
					
					Date endDate = new Date()
					Calendar calendar = new GregorianCalendar()
					calendar.setTime(endDate)
					calendar.add(calendar.DATE, project.donateTimelimit == 0?((et.getTime() - st.getTime())/(24*3600*1000)):project.donateTimelimit)
					endDate = calendar.getTime()
					
					project.endDate = endDate
					project.approveStatus = "true"
					
					//审批通过，发布项目动态，“项目通过”
					String s1 = project.id+"";
					feedBackService.insertFeedBack(SCFIREConstants.PROJECT_FEEDBACK_PASS_F+project.name+SCFIREConstants.PROJECT_FEEDBACK_PASS_E, s1,"pass")
					
				}
				weiXinService.template_status(WeiXinConstants.service_id, projectMember.openid, "项目审核成功", fmt.format(date), "发起项目", "审批通过", "您好，您发起的项目审批已经通过，如需要修改您可以在“个人中心”中继续编辑您的项目详情，如果有其他需要可以联系我们。" , WeiXinConstants.server+"/project/projectDetail?projectid="+project?.id)
				project.verified = SCFIREConstants.PROJECT_APPROVE_PASS				
				//保存系统通知消息
				SystemMessageService.sendSysMessage(SCFIREConstants.SYSTEM_MESSAGE_APPROVE_PROJECT_FRONT+project.name+SCFIREConstants.SYSTEM_MESSAGE_APPROVE_PROJECT_BACK, projectMember.id);
			}
			//项目审批拒绝
			if(opt==SCFIREConstants.PROJECT_APPROVE_REFUSE){
				weiXinService.template_status(WeiXinConstants.service_id, projectMember.openid, "项目审核失败", fmt.format(date), "发起项目", "审批失败", "您好，因为您提供的资料不齐全或不完整，您发起的项目没有审批通过，你可以在首页重新发起项目，如果有其他需要可以联系我们。" , WeiXinConstants.server+"/user/userMyProjectDetail")
				project.verified = SCFIREConstants.PROJECT_APPROVE_REFUSE
				//保存系统通知消息
				SystemMessageService.sendSysMessage(SCFIREConstants.SYSTEM_MESSAGE_REJECT_PROJECT_FRONT+project.name+SCFIREConstants.SYSTEM_MESSAGE_REJECT_PROJECT_BACK, projectMember.id);
			}
			
			//重新恢复到待审核
			if(opt==SCFIREConstants.USER_APPROVE_WAIT){
				//weiXinService.template_status(WeiXinConstants.service_id, project.member.openid, "项目重审", fmt.format(date), "发起项目", "审批重审", "您好，您发起的项目现在正在重新审批，如果不是您本人要求，可以忽略本消息，如您有疑问可以联系我们。" , "##")
				project.verified = SCFIREConstants.USER_APPROVE_WAIT
				//保存系统通知消息
				SystemMessageService.sendSysMessage(SCFIREConstants.SYSTEM_MESSAGE_REAPPROVE_PROJECT_FRONT+project.name+SCFIREConstants.SYSTEM_MESSAGE_REAPPROVE_PROJECT_BACK, projectMember.id);
				//返回到审批
				opt = SCFIREConstants.USER_APPROVE_WAIT;
			}
			
			//打回修改
			if(opt==SCFIREConstants.PROJECT_APPROVE_DRAFT){
				weiXinService.template_status(WeiXinConstants.service_id, projectMember.openid, "项目修改", fmt.format(date), "发起项目", "审批失败", "您好，因为您提供的资料不齐全或不完整，您发起的项目没有审批通过，您可以继续修改后再重新提交审核，如您有疑问可以联系我们。" , WeiXinConstants.server+"/project/edit?projectid="+project.id)
				project.verified = SCFIREConstants.PROJECT_APPROVE_MODIFY
				//保存系统通知消息
				SystemMessageService.sendSysMessage(SCFIREConstants.SYSTEM_MESSAGE_RETURN_PROJECT_FRONT+project.name+SCFIREConstants.SYSTEM_MESSAGE_RETURN_PROJECT_BACK, projectMember.id);
				//返回到审批
				opt = SCFIREConstants.USER_APPROVE_WAIT;
			}
			project.save flush:true
			
		}catch(Exception e){
			LOG.error("approve project catch exception. "+e.getMessage())
		}
		
		redirect(action:"projectApproveStatus",params: [status:opt])
		
	}

    /**
	 * 项目状态列表信息
	 * @param status
	 * @return null
	 *
	 * **/
	def projectApproveStatus(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//项目状态
		String status = params.status
		params.max = 10
		
		Member member = (Member)user
		List<Project> projects = null
		List<FRuler> fRulers = new ArrayList()
		List<ProjectClosing> projectClosings = new ArrayList()
		
 		int totalCount = 0
		def DTCreate = Project.createCriteria()
		def filterClosure = {
			if(status.equals(SCFIREConstants.PROJECT_APPROVE_PASS)){
				or {
					eq("verified",SCFIREConstants.PROJECT_APPROVE_EXPIRED)
					eq("verified",SCFIREConstants.PROJECT_APPROVE_PASS)
					eq("verified",SCFIREConstants.PROJECT_APPROVE_OVER)
					eq("verified",SCFIREConstants.PROJECT_APPROVE_EXECUTE)
					eq("verified","doing")
				}
				order("createDate","asc")
			}
			else{
				eq("verified",status)
				order("createDate","asc")
			}
		}
		
		try{
			projects = DTCreate.list(params,filterClosure)
			totalCount = DTCreate.count(filterClosure)
			if(status.equals("pass")) {
				for(def project : projects) {
					project = (Project)project
					def fRuler = FRuler.findByProject(project)
					fRulers.add(fRuler)
					def projectclosing = ProjectClosing.findByProject(project.id)
					projectClosings.add(projectclosing)
				}
			}
		}catch(Exception e){
			LOG.error("get approve project status catch exception. "+e.getMessage())
		}
		
		render view: "projectapprovestatus", model: [user:member,projects:projects,status:status,totalCount:totalCount,fRulers:fRulers,projectClosings:projectClosings]		
	}
	
	/**
	 * 用户认证审批
	 * @param user id
	 * @return null
	 *
	 * **/
	def userApprove(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//审批项目
		String userid = params.userid
		String opt = params.opt
		
		def member = null
		Date  date = new Date();
		DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		try{
			member = Member.findById(Long.valueOf(userid))
			if (member == null) {
				notFound()
				return
			}
			//用户认证审批通过
			if(opt==SCFIREConstants.PROJECT_APPROVE_PASS){
				weiXinService.template_status(WeiXinConstants.service_id, member.openid, "实名认证审核通过", fmt.format(date), "实名认证", "审批通过", "恭喜您，您的实名信息已经审核通过，您可以点击详情发起项目，如有其它需要可以联系我们。" , WeiXinConstants.server+"/project/start")
				member.verify = SCFIREConstants.PROJECT_APPROVE_PASS
				
				//保存系统通知消息
				SystemMessage systemMessage = new SystemMessage()
				systemMessage.message = SCFIREConstants.SYSTEM_MESSAGE_USER_AUTH_SUCCESS
				systemMessage.date = new Date()
				systemMessage.member = member.id
				systemMessage.save flush:true
			}
			//用户认证审批拒绝
			if(opt==SCFIREConstants.PROJECT_APPROVE_REFUSE){
				weiXinService.template_status(WeiXinConstants.service_id, member.openid, "实名认证审核失败", fmt.format(date), "实名认证", "审批失败", "很抱歉，您的实名信息不正确或资料不齐全，审核未通过，您可以点击详情修改并再次提交，如有其它需求可以联系我们。" , WeiXinConstants.server+"/user/userAuthEdit")
				member.verify = SCFIREConstants.PROJECT_APPROVE_REFUSE
				
				//保存系统通知消息
				SystemMessage systemMessage = new SystemMessage()
				systemMessage.message = SCFIREConstants.SYSTEM_MESSAGE_USER_AUTH_FAILURE
				systemMessage.date = new Date()
				systemMessage.member = member.id
				systemMessage.save flush:true
			}
			member.save flush:true
			
		}catch(Exception e){
			LOG.error("approve user catch exception. "+e.getMessage())
		}
		
		redirect(action:"userApproveStatus",params: [status:opt])
		
	}

	
	/**
	 * 触发查询用户信用评分信息
	 * @param status
	 * @return null
	 *
	 * **/
	def userCreditInfo(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//项目状态
		String uid = params.userId
		
		Member member = Member.findById(uid)
		
		//必须获取当前app路径，动态获取证书和验签位置
		Constants.APP_Root_Path = request.getSession().getServletContext().getRealPath("/")
		
		if(member != null){
			ResultEntry entry
			try{
				entry = CreditService.queryCreditInfo(member.realName, member.idNumber, member.mobile, member.bankCard)
				def credits = CreditRank.findByIdNo(member.idNumber)
				if(credits == null){
					CreditRank credit = new CreditRank(entry)
					credit.member = member
					credit.save(flush:true)
					member.creditRank = credit
				}else{
					credits.transform(entry)
					member.creditRank = credits
				}
			}
			catch(Exception e){
				LOG.error("query user creditInfo get exception."+e.getMessage())
			}
			member.save(flush: true)
		}

		render view: "userauthinfo", model: [user:member]	
	}
	
	/**
	 * 查看用户信息
	 * @param memberInstance
	 * @return null
	 *
	 * **/
	def showInfo(Member memberInstance) {

		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities

		String memberid = params.userid;
		if(memberid == null){
			notFound()
			return
		}
		
		def member = Member.findById(memberid);
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "userauthinfo", model: [user:member]
				}
			}
			json {
				
			}
		}
	}
	
	/**
	 * 用户认证状态列表信息
	 * @param status
	 * @return null
	 *
	 * **/
	def userApproveStatus(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//项目状态
		String status = params.status
		params.max = 10
		
		List<Member> users = null
		Member member = (Member)user
		int totalCount = 0
		def DTCreate = Member.createCriteria()
		def filterClosure = {
			eq("verify",status)
		}
		
		try{
			users = DTCreate.list(params,filterClosure)
			totalCount = DTCreate.count(filterClosure)
		}catch(Exception e){
			LOG.error("get approve user status catch exception. "+e.getMessage())
		}
		
		render view: "userapprovestatus", model: [user:member,users:users,status:status,totalCount:totalCount]
	}
	
	/**
	 * 管理员消息推送
	 * @param status
	 * @return null
	 *
	 * **/
	def pushMember(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities	
		params.max = 10
		
		String sendMember = params.sendMember
		println "====="+sendMember+"====="
		List<Member> users = null
		int totalCount = 0
		def DTCreate = Member.createCriteria()
		def filterClosure = {	
			if(sendMember!=""&&sendMember!=null){
				like("nickname","%"+sendMember+"%")
			}else{
			eq("pushFlag",true)
			}
			 order("id","asc")
		}
		try{
			users = DTCreate.list(params,filterClosure)
			totalCount = DTCreate.count(filterClosure)
		}catch(Exception e){
			LOG.error("get userinfo  catch exception. "+e.getMessage())
		}
		
		render view: "pushMember", model: [users:users,user:user,roles:roles,totalCount:totalCount,sendMember:sendMember]
	}
	
	/**
	 * 新增推送
	 * @return
	 */
	def addpushMember(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def memberid = params.userid
		def user = springSecurityService.getCurrentUser()
		Member member = Member.findById(Long.valueOf(memberid))
		member.pushFlag=true;
		
		def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
		DBCollection projectCollection = db.getCollection("member")
		DBObject queryCondition= new BasicDBObject()
		queryCondition.put("_id",Integer.valueOf(memberid))
		BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("pushFlag", member.pushFlag)
			)
	    projectCollection.update(queryCondition, updateParameter,true,true)
		
		redirect(action:"pushMember",params: [sendMember:""])
		
	}
	
	/**
	 * 删除推送
	 * @return
	 */
	def removepushMember(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def memberid = params.userid
		def user = springSecurityService.getCurrentUser()
		Member member = Member.findById(Long.valueOf(memberid))
		member.pushFlag=false;
		def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
		DBCollection projectCollection = db.getCollection("member")
		DBObject queryCondition= new BasicDBObject()
		queryCondition.put("_id",Integer.valueOf(memberid))
		BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("pushFlag", member.pushFlag)
			)
	    projectCollection.update(queryCondition, updateParameter,true,true)
		redirect(action:"pushMember",params: [sendMember:""])
		
	}
	
	
	

	/**
	 * 用户实名列表报告
	 * @param status
	 * @return null
	 *
	 * **/
	def userInfoReport(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		params.max = 10
		
		List<Member> users = null
		int totalCount = 0
		def DTCreate = Member.createCriteria()
		def filterClosure = {
//			or {
//				eq("verify",SCFIREConstants.USER_APPROVE_WAIT)
//				eq("verify",SCFIREConstants.USER_APPROVE_PASS)
//			}
			order("id","asc")
		}
		
		try{
			users = DTCreate.list(params,filterClosure)
			totalCount = DTCreate.count(filterClosure)
		}catch(Exception e){
			LOG.error("get userinfo report catch exception. "+e.getMessage())
		}
		
		render view: "userInfoReport", model: [users:users,user:user,roles:roles,totalCount:totalCount]
	}
	
	/**
	 * 下载用户实名信息报告
	 * @param status
	 * @return null
	 *
	 * **/
	def downuserInfoReport(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		List<Member> users = null
		List<UserInfoReport> reports = new ArrayList<UserInfoReport>();
		def DTCreate = Member.createCriteria()
		def filterClosure = {
//			or {
//				eq("verify",SCFIREConstants.USER_APPROVE_WAIT)
//				eq("verify",SCFIREConstants.USER_APPROVE_PASS)
//			}
			order("id","asc")
		}
		
		try{
			users = DTCreate.list(filterClosure)
			
			List fields = ["userid", "realName", "nickName", "mobile"]
			Map labels = ["userid": "用户id", "realName": "姓名", "nickName": "昵称", "mobile": "号码"]
			
			for(def rUser: users){
				UserInfoReport report = new UserInfoReport()
				report.userid = rUser.id
				report.realName = rUser.realName
				report.nickName = rUser.nickname
				report.mobile = rUser.mobile
				reports.add(report)
			}
			
			//下载服务
			response.contentType = grailsApplication.config.grails.mime.types[params.exportType]
			response.setHeader("Content-disposition", "attachment;filename=Report.${params.extension}")
			Map parameters = ["encoding":"UTF-8"]
			exportService.export(params.exportType, response.getOutputStream(), reports, fields, labels, null, parameters)
			return
		}catch(Exception e){
			LOG.error("down donate report catch exception. "+e.getMessage())
		}
		
		render "Export failure"
	}
	
	/**
	 * 捐赠信息列表报告
	 * @param status
	 * @return null
	 *
	 * **/
	def donateReport(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		params.max = 10
		
		List<Project> projects = null
		int totalCount = 0
		def DTCreate = Project.createCriteria()
		def filterClosure = {
			or {
				eq("verified",SCFIREConstants.PROJECT_APPROVE_EXPIRED)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_PASS)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_OVER)
				eq("verified",SCFIREConstants.PROJECT_APPROVE_EXECUTE)
			}
		}
		
		try{
			projects = DTCreate.list(params,filterClosure)
			totalCount = DTCreate.count(filterClosure)
		}catch(Exception e){
			LOG.error("get donate report catch exception. "+e.getMessage())
		}
		
		render view: "donatereport", model: [projects:projects,user:user,roles:roles,totalCount:totalCount]
	}
	
	/**
	 * 下载捐赠信息列表报告
	 * @param status
	 * @return null
	 *
	 * **/
	def downDonateReport(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		
		//审批项目
		String projectid = params.projectid
		
		def project = null
		def donates = null
		List reports = new LinkedList<>()
		
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			
			List fields = ["donateNo", "projectName", "memberName", "date", "money" , "donate_fee" , "operate_fee" ,  "type" , "operate_fee_status" ,"subDonateMemberName"]
			Map labels = ["donateNo": "捐献号", "projectName": "项目名", "memberName": "捐赠人", "money": "总额", "date": "时间" , "donate_fee" : "捐赠金额" , "operate_fee" : "平台管理费" , "type" : "捐赠平台" , "operate_fee_status" : "是否支付平台管理费", "subDonateMemberName":"一起捐发起人"]
			donates = Donate.findAllByProject(project.id)
			for(def donate: donates){
				def member = Member.findById(donate.member)
				DonateReport report = new DonateReport()
				report.donateNo = donate.donateNo
				report.projectName = project.name
				report.memberName = member.nickname
				report.date = donate.date
				report.money = donate.money
				report.donate_fee = donate.donate_fee
				report.operate_fee = donate.operate_fee
				report.type = donate.type
				report.operate_fee_status = donate.operate_fee_status
				if(donate.subProject){
					def subProject=SubProject.findById(donate.subProject)
					def submember = Member.findById(subProject.member)
					report.subDonateMemberName = submember.nickname //一起捐发起人昵称
				}else{
				report.subDonateMemberName ="" //一起捐发起人昵称
				}

				reports.add(report)
			}
			
			//下载服务
			response.contentType = grailsApplication.config.grails.mime.types[params.exportType]
			response.setHeader("Content-disposition", "attachment;filename=Report.${params.extension}")
			Map parameters = ["encoding":"UTF-8"]
			exportService.export(params.exportType, response.getOutputStream(), reports, fields, labels, null, parameters)
			return
		}catch(Exception e){
			LOG.error("down donate report catch exception. "+e.getMessage())
		}
		
		render "Export failure"
	}
	
	/**
	 * PC端保存图片信息
	 * @param null
	 * @return null
	 *
	 * **/
	def String imgSave(def file){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		UUID uuid = UUID.randomUUID()
		String img = null
		try{
			println file.getOriginalFilename()
			if(file && !file.getOriginalFilename().equals("")){
				double fileSize = file.size
				fileSize = fileSize / 1024  //以k作为计算单位
				if("mobile".equals(str)){//PC上传的图片不作压缩
					if(fileSize > 200){
						img = CompressImgUtil.compressImg(file.getBytes() , uuid.toString(),960, 0.9d)
					}
					else{
						img = FileUtil.imgSave(file.getBytes() , uuid.toString())
					}
				}
				else{
					img = FileUtil.imgSave(file.getBytes() , uuid.toString())
				}
			}
			else{
				return null;
			}
		}catch(Exception e){
			LOG.error("save image into mongodb error. "+e.getMessage())
			return null
		}
		return img
	}
	
	/**
	 * 项目信息未找到
	 * @param null
	 * @return null
	 *
	 * **/
	protected void notFound() {
		def gson = new Gson()
		withFormat {
			html {
				flash.message = "未找到该项目！"
				redirect (controller: "errors", action: "notFound")
			}
			json {
				gson.setResult(false)
				gson.setCode(404)
				gson.setInfo(["text": "未找到该项目！"])
				render gson as JSON
			}
		}
	}
	
	/************************************************************************
	 *
	 * ADMIN PC端后台管理页面
	 *
	 * ************************************************************************/
	
	/**
	 * 所有用户项目系统消息通知
	 * @param null
	 * @return null
	 *
	 * **/
	def projectSystemInfos(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
		}catch(Exception e){
			LOG.error("get user system info catch exception. "+e.getMessage())
		}
		
		render view: "projectsysinfos", model: [user:user,roles:roles]
		
	}
	
	/**
	 * create memu
	 * @param null
	 * @return null
	 *
	 * **/
	def createMainMenu(){
		def user = springSecurityService.getCurrentUser()
		Member member = (Member)user
		List<MainMenu> mainMenus= MainMenu.list("sort":"position")
		
		render view:"weixinmenu",model: [user:member,mainMenus:mainMenus,result:params.result]
	}
	
	def createsubMenu(){
		def user = springSecurityService.getCurrentUser()
		Member member = (Member)user
		List<MainMenu> mainMenus= MainMenu.list("sort":"position")
		List<SubMenu> subMenus = SubMenu.list("sort":"mainmenu")
		render view:"weixinsubmenu",model:[user:member,subMenus:subMenus,mainMenus:mainMenus]
	}
	
	/**
	 * save menu
	 */
	def saveMainMenu(MainMenu mainMenuInstance){
		if(mainMenuInstance!=null){
			MainMenu m = new MainMenu();
			m.position = mainMenuInstance.position
			m.name = mainMenuInstance.name
			m.type = mainMenuInstance.type
			m.key = mainMenuInstance.key
			m.save(flush:true);
		}
		redirect(action:"createMainMenu")
	}
	
	
	/**
	 * edit main menu
	 */
	
	def editMainMenu(MainMenu mainMenuInstance){
		if(mainMenuInstance!=null){
			MainMenu m = MainMenu.findById(mainMenuInstance.id);
			m.position = mainMenuInstance.position
			m.name = mainMenuInstance.name
			m.type = mainMenuInstance.type
			m.key = mainMenuInstance.key
			m.save(flush:true);
			
			
		}
		redirect(action:"createMainMenu")
	}
	
	
	/**
	 * delet main menu
	 */
	
	def deleteMainMenu(){
		MainMenu mainmenu = MainMenu.findById(params.mainmenuid)
		
		if(mainmenu)
			mainmenu.delete(flush:true)
		redirect(action:"createMainMenu")

	}
	
	/**
	 * delete sub menu
	 */
	def deleteSubMenu(){
		SubMenu submenu = SubMenu.findById(params.submenuid)
//		MainMenu mainMenu = submenu.mainM
//		mainMenu.removeFromSubMenus(submenu)
		if(submenu) submenu.delete(flush:true)
		redirect(action:"createsubMenu")
	}
	
	/**
	 * save sub  menu
	 */

	def saveSubMenu(SubMenu subMenuInstance){
		if(subMenuInstance!=null){
			
			MainMenu m = MainMenu.findByName(params.mainmenu)
			SubMenu sub = new SubMenu()
			sub.position = subMenuInstance.position
			sub.key =subMenuInstance.key
			sub.name = subMenuInstance.name
			sub.type = subMenuInstance.type
			sub.mainM = m
			sub.save(flush:true)
			
		}
		redirect(action:"createsubMenu")
	}
	
	/**
	 * Edit SubMenu
	 */
	
	def editSubMenu(SubMenu subMenuInstance){
		if(subMenuInstance!=null){
			println subMenuInstance.name+"  "
			SubMenu submenu = SubMenu.findById(subMenuInstance.id)
			submenu.position = subMenuInstance.position
			submenu.key = subMenuInstance.key
			submenu.type = subMenuInstance.type
			submenu.name = subMenuInstance.name
			submenu.mainM = MainMenu.findByName(params.mainmenu)
			submenu.save(flush:true)
		}
		redirect(action:"createsubMenu")
	}
	
	/**
	 * manage AutoReply
	 */
	def manageAutoReply(AutoReply autoreplyInstance){
		def user = springSecurityService.getCurrentUser()
		Member member = (Member)user
		if(autoreplyInstance!=null){
			AutoReply auto = AutoReply.findById(1)
			if(auto==null) auto = new AutoReply()
			auto.content = autoreplyInstance.content
			auto.save(flush:true)
		}
		AutoReply autoreply = AutoReply.findById(1)
		String content =""
		if(autoreply) content = autoreply.content
		render view: "weixinautoreply", model:[user:member,content:content]
	}
	
	/************************Manage PC Content*********************************************************/
	
	/**
	 * save Banner Pc
	 */	
	def saveBannerPC(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
		
			def bannerpc
			if(params.id == null){//create
				bannerpc = new Bannerpc();
				bannerpc.title = params.title
				bannerpc.description = params.description
				bannerpc.img = params.img
				bannerpc.url = params.url
				
			}else{//edit
				bannerpc = Bannerpc.findById(Integer.parseInt(params.id));
				bannerpc.title = params.title
				bannerpc.description = params.description
				bannerpc.img = params.img
				bannerpc.url = params.url
			}
			bannerpc.save(flush: true)

		}
		catch(Exception e){
			//println e
			LOG.error("save pcArticle  catch exception. "+e.getMessage())
		}
		
		redirect action:"listBannerPc"
	}
	
	def deleteBannerPc(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
			def banner = Bannerpc.findById(Integer.parseInt(params.bannerid))
			banner.delete(flush: true)
		}
		catch(Exception e){
			LOG.error("delete   catch exception. "+e.getMessage())
		}
		
		redirect action:"listBannerPc"
	}
	
	/**
	 * list Banner Pc
	 */
	def listBannerPc(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		def posterPcs = Bannerpc.findAll();
		render view: "postermanager", model:[posterPcs:posterPcs,user:user, totalCount:posterPcs.size()]
	}
	
	/**
	 * add Article Pc
	 */
	def addArticlePc(Articlepc articlepcInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def cates = Channelpc.findAll();
	
		render view: "createArticle", model:[articlepcInstance:articlepcInstance,user:user, cates:cates]
	}
	
	/**
	 * save Article Pc
	 */
	def saveArticlePc(Articlepc articlepcInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
		
			if(articlepcInstance == null){
				articlepcInstance = Articlepc.findById(params.id)
				articlepcInstance.title = params.title;
				articlepcInstance.content = params.content;
				articlepcInstance.description = params.description;
				articlepcInstance.tag = params.tag;
			}
			if(params.category != null){
				articlepcInstance.channelpc = Channelpc.findById(Integer.parseInt(params.category))
			}
			articlepcInstance.date = new Date();
			articlepcInstance.save(flush: true)
		}
		catch(Exception e){
//			println e
			LOG.error("save pcArticle  catch exception. "+e.getMessage())
		}
		
		redirect action:"listArticlePc"
	}
	
	/**
	 * edit Article Pc
	 */
	def editArticlePc(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def cates = Channelpc.findAll();

		def articlepcInstance
		try{
			articlepcInstance = Articlepc.findById(Integer.parseInt(params.articleid))
			if(articlepcInstance ==null){
				throw new Exception("article not found");
			}
		}
		catch(Exception e){
			notFound();
			LOG.error("article not found , when try to find by id: "+params.articleid+"/t exception:"+e.getMessage())
		}
		render view: "editArticle", model:[articlepcInstance:articlepcInstance, user:user, cates:cates]
	}
	
	/**
	 * delete Article Pc
	 */
	def deleteArticlePc(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
			def article = Articlepc.findById(Integer.parseInt(params.articleid))
			article.delete(flush: true)
		}
		catch(Exception e){
			LOG.error("delete pcArticle  catch exception. "+e.getMessage())
		}
		
		redirect action:"listArticlePc"
	}
	
	/**
	 * list Article Pc
	 */
	def listArticlePc(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def articles = Articlepc.findAll();
		
		render view: "articlemanager", model:[articles:articles,user:user, totalCount:articles.size()]
	}
	
	
	def categoryManage(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		def categorysArticle = Channelpc.findAll()
		def categorysParnter = Channelpartnerpc.findAll()
		
		//def posterPcs = Bannerpc.findAll();
		render view: "categorymanage", model:[user:user, categorysParnter:categorysParnter, categorysArticle:categorysArticle]
	}
	
	
	def saveCategory(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		String name = params.name
		String channel = params.channel
		String cateType = params.cateType
		
		try{
			def category;
			
			if(cateType== null){
				render "parms uncomplete";
				return;
			}
			else if (cateType.equals(SCFIREConstants.CATE_CHANNEL_PARTNER)){
				category = new Channelpartnerpc()
				category.name =name
				category.category =cateType
			}
			else if (cateType.equals(SCFIREConstants.CATE_CHANNEL_CASE)||cateType.equals(SCFIREConstants.CATE_CHANNEL_DYNAMIC)||SCFIREConstants.CATE_CHANNEL_ABOUT){
				category = new Channelpc()
				category.name =name
				category.category =cateType
			}
			category.save(flush :true)
		}
		catch(Exception e){
			LOG.error("save category failed cause by:"+ e.getMessage())
			render "failed"
			return
		}
		render "succuss"
		
	}
	
	def editCategory(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		String id = params.id
		String cateType = params.cateType
		String name = params.name
		
		try{
			def category;
			if(cateType== null){
				notFound();
				return;
			}
			else if (cateType.equals(SCFIREConstants.CATE_CHANNEL_CASE)||cateType.equals(SCFIREConstants.CATE_CHANNEL_DYNAMIC)||SCFIREConstants.CATE_CHANNEL_ABOUT){
				category = Channelpc.findById(Integer.parseInt(id))
				category.name = name
				category.category = cateType
			}
			else if (cateType.equals(SCFIREConstants.CATE_CHANNEL_PARTNER)){
				category = Channelpartnerpc.findById(Integer.parseInt(id))
				category.name = name
				category.category = cateType
			}
			category.save (flush:true)
		}
		catch(Exception e){
			LOG.error("delete category failed cause by:"+ e.getMessage())
			render "failed"
			return
		}
		render "success"
	}
	
	def deleteCategory(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		String id = params.id
		String cateType = params.type
		
		try{
			def category;
			if(cateType== null){
				notFound();
				return;
			}
			else if (cateType.equals("article")){
				category = Channelpc.findById(Integer.parseInt(id))
				
			}
			else if (cateType.equals("partner")){
				category = Channelpartnerpc.findById(Integer.parseInt(id))
			
			}
			category.delete (flush:true)
		}
		catch(Exception e){
			LOG.error("delete category failed cause by:"+ e.getMessage())
			render "failed"
			return
		}
		redirect action: "categoryManage"
	}
	
	/**
	 * list Dairy
	 */
	def listDiary(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def articles = Diary.findAll();
		
		render view: "diarymanage", model:[articles:articles, user:user, totalCount:articles.size()]
	}
	
	
	def addDiary(Diary diaryInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
	
		render view: "createDiary", model:[diaryInstance:diaryInstance,user:user]
	}
	/**
	 * saveDiary
	 */
	def saveDiary(Diary diaryInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
		
			if(diaryInstance == null){
				diaryInstance = Articlepc.findById(params.id)
				diaryInstance.title = params.title;
				diaryInstance.content = params.content;
			}
			//多张图？
			if(params.img!=null){
				diaryInstance.imgs.clear();
				if(params.img instanceof String){
					if(!params.img.equals("")){
						diaryInstance.imgs.add(params.img)
					}
					
				}
				else{
					for(int i=0;i<params.img.size();i++){
						if(!params.img.getAt(i).equals("")){
							diaryInstance.imgs.add(params.img.getAt(i))
						}
					}
				}
			}
			SimpleDateFormat dateformat =new SimpleDateFormat("yyyy/MM/dd");
			diaryInstance.date = dateformat.parse( params.edate);
			diaryInstance.save(flush: true)
		}
		catch(Exception e){
			LOG.error("save pcArticle  catch exception. "+e.getMessage())
		}
		
		redirect action:"listDiary"
	}
	
	/**
	 * editDairy
	 */
	def editDiary(Diary diaryInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities

		try{
			diaryInstance = Diary.findById(Integer.parseInt(params.articleid))
			if(diaryInstance ==null){
				throw new Exception("article not found");
			}
		}
		catch(Exception e){
			notFound();
			LOG.error("article not found , when try to find by id: "+params.articleid+"/t exception:"+e.getMessage())
		}
		render view: "editDiary", model:[diaryInstance:diaryInstance, user:user]
	}
	
	/**
	 * deleteDairy
	 */
	def deleteDiary(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
			def article = Diary.findById(Integer.parseInt(params.articleid))
			article.delete(flush: true)
		}
		catch(Exception e){
			LOG.error("delete Dairy  catch exception. "+e.getMessage())
		}
		
		redirect action:"listDiary"
	}
	
	/**
	 * delete Partner Pc
	 */
	def deletePartnerPc(Partnerpc partnerpcInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
			def partnerpc = Partnerpc.findById(Integer.parseInt(params.partnerid))
			partnerpc.delete(flush: true)
		}
		catch(Exception e){
			LOG.error("delete  catch exception. "+e.getMessage())
		}
		redirect action: "listPartnerPc"
	}
	
	/**
	 * save Partner Pc
	 */
	def savePartnerPc(Partnerpc partnerpcInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		String id = params.id
		String name = params.name
		String type = params.type
		String cateType = params.cate
		String description = params.description
		String url = params.url
		String img = params.img

		try {
			def partnerpc
			if(id == null){//create
				partnerpc = new Partnerpc();
				partnerpc.name = name
				partnerpc.type = type
				partnerpc.channelPartnepc = Channelpartnerpc.findById(Integer.parseInt(cateType))
				partnerpc.description = description
				partnerpc.url = url
				partnerpc.img = img
			}
			else{
				(Partnerpc)partnerpc = Partnerpc.findById(Integer.parseInt(id));
				partnerpc.name = name
				partnerpc.type = type
				partnerpc.channelPartnepc = Channelpartnerpc.findById(Integer.parseInt(cateType))
				partnerpc.description = description
				partnerpc.url = url
				partnerpc.img = img
			}
			partnerpc.date = new Date()
			partnerpc.save (flush:true)
		} catch (Exception e) {
			LOG.error("save partner  catch exception. "+e.getMessage());
			render "failed"
			return
		}
		
		render "succuss"
	}
	
	/**
	 * show Partner Pc
	 */
	def showPartnerPc(Partnerpc partnerpcInstance){
		
		render view: "pcpartnershow", model:[]
	}
	
	/**
	 * list Partner Pc
	 */
	def listPartnerPc(Partnerpc partnerpcInstance){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		def partners = Partnerpc.findAll();
		
		def cates = Channelpartnerpc.findAll();
		
		for(def cate: cates ){
			cate.category = "partner"
		}
		
		render view: "partnermanage", model:[partners:partners,user:user,cates:cates, totalCount:partners.size()]
	}
	
	/**
	 * edit Article Pc
	 */
	def editAbout(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def cates = Channelpc.findAll();

		def articlepcInstance
		try{
			articlepcInstance = Articlepc.findByTag('about')
			if(articlepcInstance ==null){
				articlepcInstance = new Articlepc();
				articlepcInstance.tag = 'about';
				articlepcInstance.title ="了解火堆";
			}
		}
		catch(Exception e){
			notFound();
			LOG.error("article not found , when try to find by id: "+params.articleid+"/t exception:"+e.getMessage())
		}
		render view: "editAbout", model:[articlepcInstance:articlepcInstance, user:user, cates:cates]
	}
	
	def editJoinUs(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def cates = Channelpc.findAll();

		def articlepcInstance
		try{
			articlepcInstance = Articlepc.findByTag('joinUs')
			if(articlepcInstance ==null){
				articlepcInstance = new Articlepc();
				articlepcInstance.tag = 'joinUs';
				articlepcInstance.title ="加入我们";
			}
		}
		catch(Exception e){
			notFound();
			LOG.error("article not found , when try to find by id: "+params.articleid+"/t exception:"+e.getMessage())
		}
		render view: "editAbout", model:[articlepcInstance:articlepcInstance, user:user, cates:cates]
	}
	
	/**
	 * show Channelpartner Pc
	 */
	def showChannelpartnerPc(Channelpartnerpc channelpartnerpcInstance){
		
		render view: "pcchannelpartnershow", model:[]
	}
	
	/**
	 * list Channelpartner Pc
	 */
	def listChannelpartnerPc(Channelpartnerpc channelpartnerpcInstance){
		
		render view: "pcchannelpartnerlist", model:[]
	}
	
	//-------------------------------fundPool start----------------------------------------
	
	/**
	 * 资金池列表
	 * @param null
	 * @return null
	 *
	 * **/
	def listFund(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		params.max = 20
		
		List<FundPool> fundpools = null
		int totalCount = 0
		def DTCreate = FundPool.createCriteria()
		def filterClosure = {
			order("id","asc")
		}
		
		try{
			fundpools = DTCreate.list(params,filterClosure)
			totalCount = DTCreate.count(filterClosure)
		}catch(Exception e){
			LOG.error("get fundlist catch exception. "+e.getMessage())
		}
		render view: "fundPoolList", model:[fundpools:fundpools, user:user, totalCount:totalCount]
	}
	/**
	 * 添加资金池
	 * @param fundpoolInstance
	 * @return null
	 *
	 * **/
	def addFund(FundPool fundpoolInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		render view: "createFund", model:[fundpoolInstance:fundpoolInstance,user:user]
	}	
	/**
	 * 编辑资金池
	 * @param fundpoolInstance
	 * @return null
	 *
	 * **/
	def editFund(FundPool fundpoolInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		try{
			fundpoolInstance = FundPool.findById(Integer.parseInt(params.fundid))
			if(fundpoolInstance ==null){
				throw new Exception("fundpool not found");
			}
		}
		catch(Exception e){
			notFound();
			LOG.error("fundpool not found , when try to find by id: "+params.articleid+"/t exception:"+e.getMessage())
		}
		render view: "editFund", model:[fundpoolInstance:fundpoolInstance,user:user]
	}
	/**
	 * 保存资金池
	 * @param fundpoolInstance
	 * @return null
	 *
	 * **/
	def saveFundPool(FundPool fundpoolInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
		
			if(fundpoolInstance == null){
				fundpoolInstance = FundPool.findById(params.id)
				fundpoolInstance.name = params.name;
				fundpoolInstance.type = params.type;
				fundpoolInstance.fullName = params.fullName;
				fundpoolInstance.contacter = params.contacter;
				fundpoolInstance.tel = params.tel;
				fundpoolInstance.email = params.email;
				fundpoolInstance.description = params.description;
			}
			//多张图？
			if(params.img!=null){
				List<String> extraPic = new LinkedList<String>();
				if(params.img instanceof String){
					if(!params.img.equals("")){
						extraPic.add(params.img)
						fundpoolInstance.extraPic = extraPic						
					}
					
				}
				else{
					for(int i=0;i<params.img.size();i++){
						if(!params.img.getAt(i).equals("")){
							extraPic.add(params.img.getAt(i))
						}
					}
				}
				//上传图片路径集
				fundpoolInstance.extraPic = extraPic
			}
			if(params.imgcoverPic != null){
				fundpoolInstance.coverPic = params.imgcoverPic
			}
			fundpoolInstance.createDate = new Date()
			fundpoolInstance.status = "create"
			fundpoolInstance.member = user
			fundpoolInstance.save(flush: true)
		}
		catch(Exception e){
			LOG.error("save fundPool  catch exception. "+e.getMessage())
		}
		
		redirect action:"listFund"
	}
	
	/**
	 * 编辑资金池金额
	 * @param fundpoolInstance id
	 * @return null
	 *
	 * **/
	def editFundMoney(FundPool fundpoolInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		try{
			fundpoolInstance = FundPool.findById(Integer.parseInt(params.fundid))
			if(fundpoolInstance ==null){
				throw new Exception("fundpool not found");
			}
		}
		catch(Exception e){
			notFound();
			LOG.error("edit fund money catch exception。"+e.getMessage())
		}
		render view: "editFundMoney", model:[fundpoolInstance:fundpoolInstance,user:user]
	}
	
	/**
	 * 编辑资金池金额
	 * @param fundpoolInstance id
	 * @return null
	 *
	 * **/
	def saveFundMoney(FundPool fundpoolInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		String plusmoney = params.plusmoney
		String minusmoney = params.minusmoney
		String moneyString = params.money
		String mark = params.mark
		int money = 0
		if(moneyString){
			money = Integer.valueOf(moneyString)
		}
		money = money *100
		
		FOperate foperate = new FOperate()
		
		try{
			fundpoolInstance = FundPool.findById(Integer.parseInt(params.fundid))
			if(fundpoolInstance ==null){
				throw new Exception("fundpool not found");
			}
			foperate.fundpool = fundpoolInstance
			foperate.optDate = new Date()
			
			if(plusmoney){
				fundpoolInstance.totalCount += money
				foperate.operate = "plusmoney"
				foperate.income = money
			}
			if(minusmoney){
				foperate.operate = "minusmoney"
				if( (fundpoolInstance.totalCount - fundpoolInstance.donateAssigned) - money <0){
					throw new Exception("money too much exception!");
				}else{
					fundpoolInstance.totalCount -= money
					foperate.outcome = money
				}
			}
			if(mark){
				foperate.mark = mark
			}
			foperate.save flush:true
			fundpoolInstance.save flush:true
			
		}catch(Exception e){
			notFound();
			LOG.error("save fund money catch exception。"+e.getMessage())
		}
		redirect action:"listFund"
	}
	
	/**
	 * 爱心池账户明细
	 * @param null
	 * @return null
	 *
	 * **/
	def listFundPoolDetail(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		params.max = 20
		
		List<FOperate> fOperates = null
		int totalCount = 0
		def DTCreate = FOperate.createCriteria()
		def filterClosure = {
			order("id","asc")
			isNotNull("fundpool")
		}
		
		try{
			fOperates = DTCreate.list(params,filterClosure)
			totalCount = DTCreate.count(filterClosure)

			for(def fOperate : fOperates) {
				fOperate = (FOperate)fOperate
			}
		}catch(Exception e){
			LOG.error("get fundlist catch exception. "+e.getMessage())
		}
		render view: "fundPoolListDetail", model:[fOperates:fOperates, user:user,totalCount:totalCount]
	}
	
	/**
	 * 下载爱心池详细信息列表报告
	 * @param status
	 * @return null
	 *
	 * **/
	def downFundPoolDetailReport(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		
		//审批爱心池
		List<FOperate> fOperates = null
		def DTCreate = FOperate.createCriteria()
		def filterClosure = {
			order("id","asc")
			isNotNull("fundpool")
		}
		
		try{
			fOperates = DTCreate.list(params,filterClosure)
		}catch(Exception e){
			LOG.error("get fundPoolDetaillist catch exception. "+e.getMessage())
		}
		
		List reports = new LinkedList<>()
		
		try{
			List fields = ["fundPoolId", "fundPoolName", "operate", "outcome", "income" , "rule" , "projectName" ,  "optDate" ,"mark"]
			Map labels = [ "fundPoolId":"爱心池ID", "fundPoolName":"爱心池名称", "operate":"操作类型", "outcome":"支出", "income":"收入" , "rule" :"配捐比例" , "projectName":"项目名称" ,  "optDate":"操作时间" ,"mark":"备注说明"]
			for(def fOperate : fOperates) {
				FundPoolDetailReport report = new FundPoolDetailReport()
				report.fundPoolId = fOperate.fundpool.id
				report.fundPoolName = fOperate.fundpool.name
				report.operate = fOperate.operate
				report.outcome = fOperate.outcome
				report.income = fOperate.income
				report.rule = fOperate.rule
				if(fOperate.project) {
					report.projectName = fOperate.project.name
				}
				report.optDate = fOperate.optDate
				report.mark = fOperate.mark
				reports.add(report)
			}
			
			//下载服务
			response.contentType = grailsApplication.config.grails.mime.types[params.exportType]
			response.setHeader("Content-disposition", "attachment;filename=Report.${params.extension}")
			Map parameters = ["encoding":"UTF-8"]
			exportService.export(params.exportType, response.getOutputStream(), reports, fields, labels, null, parameters)
			return
		}catch(Exception e){
			LOG.error("down fundPoolDetail report catch exception. "+e.getMessage())
		}
		
		render "Export failure"
	}
	
	
	//------------------------------fundPool-end-------------------------------------------
	
	//-------------------------------bandFund start----------------------------------------	
	/**
	 * 项目绑定资金池金额
	 * @param null
	 * @return null
	 *
	 * **/
	def bandFundEdit(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = (Member)springSecurityService.getCurrentUser()
		
		def projectid = params.id
		def project
		if(projectid){
			project = Project.findByIdAndVerifiedInList(projectid , ["pass","execute","expired","over"])
		}
		def fruler = FRuler.findByProject(project)
		List<FundPool> fundPools = FundPool.list()
		render view : "bandFundEdit" , model : [project : project , fruler : fruler ,fundPools : fundPools , user : user]
	}
	
	/**
	 * 项目绑定资金池金额
	 * @param null
	 * @return null
	 *
	 * **/
	def saveBandFund(){
		def json = [:]
		def moneyString = params.money
		int money = 0
		if(moneyString){
			money = Double.parseDouble(moneyString) * 100
		}
		def mark = params.mark
		
		//项目查找
		def projectid = params.projectid
		def project
		if(projectid){
			project = Project.findByIdAndVerifiedInList(projectid , ["pass","execute","expired","over"])
		}
		//资金池查找
		def fundPoolid = params.poolid
		def fundPool
		if(fundPoolid){
			fundPool = FundPool.findById(fundPoolid)
		}
		
		if(project && fundPool){
			//配捐规则查找
			def fruler = FRuler.findByProject(project)
			
			if("false".equals(fruler?.status)){
				json.put("info" , "项目配捐已结束，不能再次配捐！");
				render json as JSON
				return
			}
			
			//保存爱心池操作记录 ,over状态需要配捐规则信息在下面单独处理
			if("add".equals( params.operate) || "minus".equals( params.operate)){
				def foperate = new FOperate()
				foperate.fundpool = fundPool
				foperate.project = project
				foperate.operate = params.operate
				if("add".equals( params.operate) ){
					foperate.outcome = 	money
				}
				if("minus".equals( params.operate) ){
					foperate.income = 	money
				}
				if(fruler){
					foperate.rule = fruler.regular
				}else{
					foperate.rule = params.regular
				}
				foperate.mark = mark
				foperate.optDate = new Date()
				foperate.save(flush:true)
			}

			
			//更新
			if(fruler){
				def operate = params.operate
				//增加金额
				if("add".equals( operate) ){
					//如果资金当前可够分配
					if((fundPool.totalCount  - fundPool.donateAssigned) >= money){
						fruler.bandfund += money
						fruler.updateDate = new Date()
						fundPool.donateAssigned += money
						fruler.save(flush : true)
						fundPool.save(flush : true)
						json.put("info" , "增加金额"+moneyString+"元成功！");
						render json as JSON
						return
					}
				}else if("minus".equals( operate)){
					//减少金额
					if((fruler.bandfund - money) >= 0){
						fruler.bandfund -= money
						fruler.updateDate = new Date()
						fundPool.donateAssigned -= money
						fruler.save(flush : true)
						fundPool.save(flush : true)
						json.put("info" , "减少金额"+moneyString+"元成功！");
						render json as JSON
						return
					}
				}else if("over".equals( operate)){
					//结束项目
					fruler.status = "false"
					fruler.save(flush : true)
					int restfund = fruler.bandfund - fruler.donatefund			
					if(restfund>0){
						fundPool.donateAssigned -= restfund
						fundPool.save(flush : true)
					}
					
					//over操作记录
					def foperate = new FOperate()
					foperate.fundpool = fundPool
					foperate.project = project
					foperate.operate = "over"
					int frulerOverMoney = fruler.bandfund - fruler.donatefund
					if(frulerOverMoney < 0){
						frulerOverMoney = 0
					}
					foperate.income = 	frulerOverMoney
					foperate.rule = fruler.regular
					foperate.mark = mark
					foperate.optDate = new Date()
					foperate.save(flush:true)
					json.put("info" , "结束项目"+project.name+"成功！");
					render json as JSON
					return
					
				}
			}else{
				//新增
				//如果资金当前可够分配
				if((fundPool.totalCount  - fundPool.donateAssigned) >= money){
					fruler = new FRuler()
					fruler.fundPool = fundPool
					fruler.project = project
					fruler.regular = params.regular
					fruler.bandfund = money
					fruler.status = "true"
					fruler.createDate = new Date()
					fruler.updateDate = new Date()
					fruler.save(flush : true)
					
					fundPool.donateAssigned += money
					fundPool.save(flush : true)
					json.put("info" , "增加金额"+moneyString+"元成功！");
					render json as JSON
					return
				}
			}
		}
		json.put("info" , "参数缺失，操作失败！");
		render json as JSON
		return
	}	
	//-------------------------------bandFund end----------------------------------------
	
	//TODO delete it after the spring festival activity finished.
	/**
	 * @return
	 */
	def showRedEnvelopeTicket(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		def user = (Member)springSecurityService.getCurrentUser()
		
		def tickets
		try{
			tickets = RedEnvelope.get(1)
			if(tickets == null){
				tickets = new RedEnvelope();
				tickets.ticket = ""
				tickets.save(flush: true)
			}
		}
		catch(Exception e){
			LOG.error("save RedEnvelope  catch exception. "+e.getMessage())
		}
		render view:"editRedEvTicket", model:[tickets:tickets, user:user]
	}
	
	/**
	 * @return
	 */
	def saveRedEnvelopeTicket(RedEnvelope redEnvelopeInstance){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		try{
			if(redEnvelopeInstance == null){
				redEnvelopeInstance = RedEnvelope.findById(params.id)
				redEnvelopeInstance.ticket = params.ticket;
			}
			redEnvelopeInstance.save(flush: true)
			
		}
		catch(Exception e){
			LOG.error("save ReEnvelope  catch exception. "+e.getMessage())
		}
		redirect action: "showRedEnvelopeTicket"
		
	}
	
	def switchRedEnve(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		try{
			def tickets = RedEnvelope.get(1)
			if(tickets != null){
				tickets.stats = tickets.stats? false:true;
			}
			tickets.save(flush: true)
			
		}
		catch(Exception e){
			LOG.error("switch ReEnvelope  catch exception. "+e.getMessage())
		}
		redirect action: "showRedEnvelopeTicket"
		
	}

	
	/**
	 * 捐赠详细信息列表报告
	 * @param status
	 * @return null
	 *
	 * **/
	def donateDetail(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		params.max = 20
		
		//接收参数
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd")
		def donateID 
		def userID
		def beginDate
		def endDate
		def nickname = params.nickname
		def types = params.types
		def projectName = params.projectName
		def verified = params.verified
		
		List<Donate> donates = new ArrayList()
		int totalCount = 0
		def DTCreate = Donate.createCriteria()

			//参数类型转换
		try {
			if(params.donateID) {
				donateID = Long.parseLong(params.donateID)
			}
			
			if(params.userID) {
				userID = Long.parseLong(params.userID)
			}
			
			if(null!=params.beginDate&&!params.beginDate.equals("")&&!params.beginDate.equals("null")) {
				beginDate = df.parse(request.getParameter("beginDate"))
				
			}
			
			if(null!=params.endDate&&!params.endDate.equals("")&&!params.endDate.equals("null")) {
				endDate = df.parse(request.getParameter("endDate"))
				
			}
			
			
		} catch(NumberFormatException e) {
			LOG.error("get donate report catch exception. "+e.getMessage())
		}
		
		//没有项目和昵称搜索信息
		if((nickname==null||nickname=="")&&(projectName==null||projectName=="")&&(verified==null||verified=="")) {
			def	filterClosure = {
					and{
						
						if(types) {
							eq("type",types)
						}
						if(donateID) {
							eq("id", donateID)
						}
						if(userID) {
							eq("member", userID)
						}
						
						if(beginDate!=null&&beginDate!=""&&endDate!=null&&endDate!="") {
							between("date",beginDate,endDate)
						}
					}
					
					order("id","asc")
				}
			try{
				donates = DTCreate.list(params,filterClosure)
				totalCount = DTCreate.count(filterClosure)
			}catch(Exception e){
				LOG.error("get donate report catch exception. "+e.getMessage())
			}
			
			//选出所有项目再过滤
		} else if(nickname==null||nickname=="") {
			
			List<Project> projects = null
			def PCreate = Project.createCriteria()
			def fc = {
				if(projectName) {
					like("name","%"+projectName+"%")
				}
				if(verified) {
					eq("verified",verified)
				}
				order("id","asc")
			}
			try{
				projects = PCreate.list(fc)
				if(projects!=null) {
					for(def project : projects) {
						project = (Project)project
						donates.addAll(project.donates)
						
					}
					for(int i=0;i<donates.size();i++) {
						def donate = (Donate)donates.get(i)
						boolean delete = false
						
						if(types) {
							if(!donate.type.equals(types)) {
								delete = true
							} 
						}
						
						if(donateID) {
							if(!donate.id.equals(donateID)) {
								delete = true
							} 
						}
						
						if(userID) {
							if(!donate.member.id.equals(userID)) {
								delete = true
							} 
						}
						
						if(beginDate&&endDate) {
							if(donate.date.after(beginDate)&&donate.date.before(endDate)) {
								delete = true
							}
						}
						if(delete) {
							donates.remove(i)
							i--
						}
					}
					if(donates==null) {
						totalCount = 0
					}else {
						totalCount = donates.size()
					} 
					
				}
				//分页功能
				if(params.offset) {
					int start = Integer.parseInt(params.offset)
					int end = start + params.max
					if(end > totalCount) {
						end = totalCount
					}
					donates = donates.subList(start,end)
				} else {
					if(totalCount>0&&totalCount < params.max ) {
						donates = donates.subList(0,totalCount)
					}else if(totalCount!=0) {
						donates = donates.subList(0,params.max)
					}
				}
			}catch(Exception e){
				LOG.error("get donate report catch exception. "+e.getMessage())
			}
//			选出所有成员再过滤
		} else {
			List<Member> members = null
			
			def MCreate = Member.createCriteria()
			def fc = {
				if(nickname) {
					like("nickname","%"+nickname+"%")
				}
				order("id","asc")
			}
			try{
				members = MCreate.list(fc)
				if(members!=null) {
					for(def member : members) {
						member = (Member)member
						def donates2= Donate.findAllByMember(member.id)
						donates.addAll(donates2)
						
					}
					
					for(int i=0;i<donates.size();i++) {
						def donate = (Donate)donates.get(i)
						boolean delete = false
						
						if(types) {
							if(!donate.type.equals(types)) {
								delete = true
							}
						}
						
						if(donateID) {
							if(!donate.id.equals(donateID)) {
								delete = true
							}
						}
						
						if(userID) {
							if(!donate.member.id.equals(userID)) {
								delete = true
							}
						}
						
						if(beginDate&&endDate) {
							if(donate.date.after(beginDate)&&donate.date.before(endDate)) {
								delete = true
							}
						}
						
						if(verified) {
							if(!donate.project.verified.equals(verified)) {
								delete = true
							}
						} 
						
						if(projectName) {
							if(!donate.project.name.contains(projectName)) {
								delete = true
							}
						}
						
						if(delete) {
							donates.remove(i)
							i--
						}
					}
					if(donates==null) {
						totalCount = 0
					}else {
						totalCount = donates.size()
					}
					
				}
				//分页功能
				if(params.offset) {
					int start = Integer.parseInt(params.offset)
					int end = start + params.max
					if(end > totalCount) {
						end = totalCount
					}
					donates = donates.subList(start,end)
				} else {
					if(totalCount>0&&totalCount < params.max ) {
						donates = donates.subList(0,totalCount)
					}else if(totalCount!=0) {
						donates = donates.subList(0,params.max)
					}
				}
			}catch(Exception e){
				LOG.error("get donate report catch exception. "+e.getMessage())
			}
			
		}
		JSONArray fRulesjson = new JSONArray()
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		for(Donate d:donates){
			JSONObject json = new JSONObject()
			json.put("id", d.id)
			json.put("memberid", d.id)
			json.put("id", d.member)
			def member = Member.findById(d.member)
			json.put("nickname", member?.nickname)
			def donateProject = Project.findById(d.project)
			json.put("projectName", donateProject.name)
			json.put("verified", donateProject.verified)
			json.put("money", d.money)
			json.put("donate_fee", d.donate_fee)
			
			json.put("date", sdf.format(d.date).substring(5))
			json.put("type", d.type)
			if(d?.subProject){
				def subproject = SubProject.findById(d.subProject)
				def submember = Member.findById(subproject.member)
				json.put("subnickname", submember?.nickname)
			}else{
			json.put("subnickname", "")
			}
			def fDoante = FDonate.findByDonate(d.id)
			if(fDoante){
				def fundPool = FundPool.findById(fDoante.fundPool)
				json.put("fdonate_fee", fDoante.donate_fee)
				json.put("fundpoolname", fundPool.name)
			}else{
			json.put("fundpoolname", "")
			json.put("fdonate_fee", 0)
			}
			
			fRulesjson.add(json)
		}
			
		render view: "donateDetailreport", model: [fRulesjson:fRulesjson,user:user,roles:roles,totalCount:totalCount,
			donateID:donateID,userID:userID,types:types,verified:verified,beginDate:params.beginDate,endDate:params.endDate,
			projectName:projectName,nickname:nickname]
	}
	
	/**
	 * 下载捐赠详细信息列表报告
	 * @param status
	 * @return null
	 *
	 * **/
	def downDonateDetailReport(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		//接收参数
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd")
		def donateID 
		def userID
		def beginDate
		def endDate
		def nickname = params.nickname
		def types = params.types
		def projectName = params.projectName
		def verified = params.verified
		
		List<Donate> donates = new ArrayList()
		int totalCount = 0
		def DTCreate = Donate.createCriteria()
		
		try {
			if(params.donateID!=null&&!params.donateID.equals("")&&!params.donateID.equals("null")) {
				donateID = Long.parseLong(params.donateID)
			}
			
			if(params.userID!=null&&!params.userID.equals("")&&!params.userID.equals("null")) {
				userID = Long.parseLong(params.userID)
			}
			
			if(null!=params.beginDate&&!params.beginDate.equals("")&&!params.beginDate.equals("null")) {
				beginDate = df.parse(request.getParameter("beginDate"))
				
			}
			
			if(null!=params.endDate&&!params.endDate.equals("")&&!params.endDate.equals("null")) {
				endDate = df.parse(request.getParameter("endDate"))
				
			}
			
			
		} catch(NumberFormatException e) {
			LOG.error("get donate report catch exception. "+e.getMessage())
		}
		
		if((nickname==null||nickname=="")&&(projectName==null||projectName=="")&&(verified==null||verified=="")) {
			def	filterClosure = {
					and{
						
						if(types) {
							eq("type",types)
						}
						if(donateID) {
							eq("id", donateID)
						}
						if(userID) {
							eq("member", userID)
						}
						
						if(beginDate!=null&&beginDate!=""&&endDate!=null&&endDate!="") {
							between("date",beginDate,endDate)
						}
					}
					
					order("id","asc")
				}
			try{
				donates = DTCreate.list(filterClosure)
				totalCount = DTCreate.count(filterClosure)
			}catch(Exception e){
				LOG.error("get donate report catch exception. "+e.getMessage())
			}
		} else if(nickname==null||nickname=="") {
			
			List<Project> projects = null
			def PCreate = Project.createCriteria()
			def fc = {
				if(projectName) {
					like("name","%"+projectName+"%")
				}
				if(verified) {
					eq("verified",verified)
				}
				order("id","asc")
			}
			try{
				projects = PCreate.list(fc)
				if(projects!=null) {
					for(def project : projects) {
						project = (Project)project
						donates.addAll(project.donates)
						
					}
					for(int i=0;i<donates.size();i++) {
						def donate = (Donate)donates.get(i)
						boolean delete = false
						
						if(types) {
							if(!donate.type.equals(types)) {
								delete = true
							} 
						}
						
						if(donateID) {
							if(!donate.id.equals(donateID)) {
								delete = true
							} 
						}
						
						if(userID) {
							if(!donate.member.id.equals(userID)) {
								delete = true
							} 
						}
						
						if(beginDate&&endDate) {
							if(donate.date.after(beginDate)&&donate.date.before(endDate)) {
								delete = true
							}
						}
						if(delete) {
							donates.remove(i)
							i--
						}
					}
					if(donates==null) {
						totalCount = 0
					}else {
						totalCount = donates.size()
					} 
					
				}
			}catch(Exception e){
				LOG.error("get donate report catch exception. "+e.getMessage())
			}
		} else {
			List<Member> members = null
			
			def MCreate = Member.createCriteria()
			def fc = {
				if(nickname) {
					like("nickname","%"+nickname+"%")
				}
				order("id","asc")
			}
			try{
				members = MCreate.list(fc)
				if(members!=null) {
					for(def member : members) {
						member = (Member)member
						def donates2 = Donate.findAllByMember(member.id)
						donates.addAll(donates2)
						
					}
					
					for(int i=0;i<donates.size();i++) {
						def donate = (Donate)donates.get(i)
						boolean delete = false
						
						if(types) {
							if(!donate.type.equals(types)) {
								delete = true
							}
						}
						
						if(donateID) {
							if(!donate.id.equals(donateID)) {
								delete = true
							}
						}
						
						if(userID) {
							if(!donate.member.id.equals(userID)) {
								delete = true
							}
						}
						
						if(beginDate&&endDate) {
							if(donate.date.after(beginDate)&&donate.date.before(endDate)) {
								delete = true
							}
						}
						
						if(verified) {
							if(!donate.project.verified.equals(verified)) {
								delete = true
							}
						} 
						
						if(projectName) {
							if(!donate.project.name.contains(projectName)) {
								delete = true
							}
						}
						
						if(delete) {
							donates.remove(i)
							i--
						}
					}
					if(donates==null) {
						totalCount = 0
					}else {
						totalCount = donates.size()
					}
					
				}
				
			}catch(Exception e){
				LOG.error("get donate report catch exception. "+e.getMessage())
			}
			
		}
				
		//审批项目
		
		try{
			
			List reports = new LinkedList<>()
			List fields = ["donateID", "userID", "nickname", "projectName", "verified" , "money" , "donate_fee" ,  "operate_fee" , 
				"operate_fee_status" ,"date","type","memberRaise","status","fundPool","FDonate_fee"]
			Map labels = ["donateID":"捐赠ID", "userID":"用户ID", "nickname":"昵称", "projectName":"项目名称", "verified":"项目状态" , "money":"总额" , "donate_fee":"捐赠金额 " ,  "operate_fee":"平台管理费" , 
				"operate_fee_status":"管理费" ,"date":"捐赠时间","type":"支付渠道","memberRaise":"一起捐发起人","status":"交易状态","fundPool":"配捐爱心池","FDonate_fee":"配捐金额"] 
			for(def donate: donates){
				def member = Member.findById(donate.member)
				def project = Project.findById(donate.project)
				DonateDetailReport report = new DonateDetailReport()
				report.donateID = donate.id
				report.userID = donate.member
				report.nickname = member.nickname
				report.projectName = project.name
				report.verified = project.verified
				report.money = donate.money
				report.donate_fee = donate.donate_fee
				report.operate_fee = donate.operate_fee
				report.operate_fee_status = donate.operate_fee_status
				report.date = donate.date
				report.type = donate.type
				if(donate.subProject==null) {
					report.memberRaise = ""
				}else {
					def subproject=SubProject.findById(donate.subProject)
					def submember= Member.findById(subProject?.member)
					report.memberRaise = submember?.nickname
				}
				report.status = donate.status
				if(donate.fDonate==null) {
					report.fundPool = ""
					report.FDonate_fee = ""
				} else {
					def fDonate = FDonate.findById(donate.fDonate)
					def fundPool= FundPool.findById(fDonate.fundPool)
					report.fundPool = fundPool.name
					report.FDonate_fee = fDonate.donate_fee
				}
				reports.add(report)
			}
			
			//下载服务
			response.contentType = grailsApplication.config.grails.mime.types[params.exportType]
			response.setHeader("Content-disposition", "attachment;filename=Report.${params.extension}")
			Map parameters = ["encoding":"UTF-8"]
			exportService.export(params.exportType, response.getOutputStream(), reports, fields, labels, null, parameters)
			return
		}catch(Exception e){
			LOG.error("down donate report catch exception. "+e.getMessage())
		}
		
		render "Export failure"
	}
	
	
	/**
	 * 项目筹款明细信息列表报告
	 * @param status
	 * @return null
	 *
	 * **/
	def listProjectFeeDetail(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		params.max = 20
		
		//接收参数
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss")
		def projectID 
		def projectName = params.projectName
		def userID    //项目发起人ID
		def verified = params.verified	  //项目状态
		
		List<FRuler> fRulers = new ArrayList() 
		List<Project> projects = null
		List<Integer> durations = new ArrayList() //众筹时间
		int totalCount = 0
		def PCreate = Project.createCriteria()
		
		//参数类型转换

			if(params.projectID) {
				projectID = Long.parseLong(params.projectID)
			}
			
			if(params.userID) {
				userID = Long.parseLong(params.userID)
			}
			
			def	filterClosure = {
					and{
						
						if(projectID) {
							eq("id",projectID)
						}

						if(userID) {
							eq("member", userID)
						}
						
						if(verified) {
							eq("verified",verified)
						}
						
						if(projectName) {
							like("name","%"+projectName+"%")
						}
						
					}
					
					order("id","asc")
				}
			try{
				projects = PCreate.list(params,filterClosure)
				totalCount = PCreate.count(filterClosure)
				
				for(def project : projects) {
					project = (Project)project
					def fRuler = FRuler.findByProject(project)
					fRulers.add(fRuler)
					if(project.startDate&&project.endDate) {
						Date begin = sdf.parse( sdf.format(project.startDate))
						Date finish = sdf.parse( sdf.format(project.endDate))
						Calendar cal = Calendar.getInstance()
						cal.setTime(begin)
						long start = cal.getTimeInMillis()
						cal.setTime(finish)
						long end = cal.getTimeInMillis()
						durations.add(Integer.parseInt(String.valueOf((end-start)/(1000*3600*24))))
					} else {
						durations.add(0)
					}
				}
				
			}catch(Exception e){
				LOG.error("get donate report catch exception. "+e.getMessage())
			}
			
		render view: "listProjectFeeDetail", model: [durations:durations,projects:projects,user:user,roles:roles,totalCount:totalCount,
			projectID:projectID,userID:userID,verified:verified,projectName:projectName,fRulers:fRulers]
	}
	
	/**
	 * 下载项目筹款明细信息列表报告
	 * @param status
	 * @return null
	 *
	 * **/
	def downProjectFeeDetailReport(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		//接收参数
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss")
		def projectID
		def projectName = params.projectName
		def userID    //项目发起人ID
		def verified = params.verified	  //项目状态
		
		List<Project> projects = null
		List<Integer> durations = new ArrayList() //众筹时间
		int totalCount = 0
		def PCreate = Project.createCriteria()
		
		//参数类型转换

			if(params.projectID!=null&&!params.projectID.equals("")&&!params.projectID.equals("null")) {
				projectID = Long.parseLong(params.projectID)
			}
			
			if(params.userID!=null&&!params.userID.equals("")&&!params.userID.equals("null")) {
				userID = Long.parseLong(params.userID)
			}
			
			def	filterClosure = {
					and{
						if(projectID) {
							eq("id",projectID)
						}

						if(userID) {
							eq("member", userID)
						}
						
						if(verified) {
							eq("verified",verified)
						}
						
						if(projectName) {
							like("name","%"+projectName+"%")
						}
						
					}
					
					order("id","asc")
				}
			try{
				projects = PCreate.list(filterClosure)
				totalCount = PCreate.count(filterClosure)
	
				for(def project : projects) {
					project = (Project)project
					if(project.startDate&&project.endDate) {
						Date begin = sdf.parse( sdf.format(project.startDate))
						Date finish = sdf.parse( sdf.format(project.endDate))
						Calendar cal = Calendar.getInstance()
						cal.setTime(begin)
						long start = cal.getTimeInMillis()
						cal.setTime(finish)
						long end = cal.getTimeInMillis()
						durations.add(Integer.parseInt(String.valueOf((end-start)/(1000*3600*24))))
					} else {
						durations.add(0)
					}
				}
				
			}catch(Exception e){
				LOG.error("get donate report catch exception. "+e.getMessage())
			}
		//审批项目
		
		try{
			DecimalFormat decimalFormat=new DecimalFormat("###.##");
			List reports = new LinkedList<>()
			List fields = ["projectID", "userID", "projectName", "duration","verified" , "donateNum" , "amount" ,  "money" ,
				"payment" ,"fundPoolName","FDonate_fee","mark"]
			Map labels = ["projectID":"项目ID", "userID":"发起人ID", "projectName":"项目名称", "duration":"筹款天数","verified":"项目状态" ,
				"donateNum":"捐赠人次","amount":"目标金额","money":"已筹金额","payment":"支付金额","fundPoolName":"配捐爱心池","FDonate_fee":"配捐金额","mark":"备注"]
			def i = 0
			for(def project:projects){
				project = (Project)project
				def fRuler = FRuler.findByProject(project)
				ProjectFeeDetailReport report = new ProjectFeeDetailReport()
				report.projectID = project.id
				report.userID = project.member
				report.projectName = project.name
				report.duration = durations.get(i)
				report.verified = project.verified
				report.donateNum = project.donateNum
				report.amount = project.amount
				report.money = decimalFormat.format(project.amount - project.rest)
				report.payment = ""
				if(fRuler){
					report.fundPoolName = fRuler.fundPool.name
					report.FDonate_fee = fRuler.donatefund
				}else {
					report.fundPoolName = ""
					report.FDonate_fee = ""
				}
				report.mark = ""
				i++
				reports.add(report)
			}
			
			//下载服务
			response.contentType = grailsApplication.config.grails.mime.types[params.exportType]
			response.setHeader("Content-disposition", "attachment;filename=Report.${params.extension}")
			Map parameters = ["encoding":"UTF-8"]
			exportService.export(params.exportType, response.getOutputStream(), reports, fields, labels, null, parameters)
			return
		}catch(Exception e){
			LOG.error("down donate report catch exception. "+e.getMessage())
		}
		
		render "Export failure"
	}

	/**
	 * 项目审核管理
	 * @param status
	 * @return null
	 *
	 * **/
	def projectManage(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取项目
		def projectid = params.projectid
		if(!projectid) {
			redirect(action:"projectApproveStatus",params: [status:SCFIREConstants.USER_APPROVE_WAIT])
			return 
		}
		def project = null
		List<FOperate> foperates = new ArrayList()
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			
			for(def foperate : project.foperates) {
				foperate = (FOperate)foperate
				if(foperate.operate!="add"&&foperate.operate!="minus") {
					foperates.add(foperate)
				}
				
			}
			
		}catch(Exception e){
			LOG.error("manage project catch exception. "+e.getMessage())
		}
		render view:"projectManage",model:[user:user,roles:roles,foperates:foperates,project:project]
	}
	
	/**
	 * 项目内容审核结果处理
	 * @param status
	 * @return null
	 *
	 * **/
	def saveProjectApprove() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取项目
		def projectid = params.projectid
		def project = null
		def opt = null
		
		if(!params.check) {
			redirect(action:"projectApproveStatus",params: [status:"wait"])
			return
		}
		
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			Date date = new Date()
			def foperate = new FOperate()
			foperate.operate = "contentApprove"
			foperate.result = params.check
			if(params.excuse&&!params.excuse.equals("审核理由(可选)")) {
				foperate.excuse = params.excuse
			}
			foperate.project = project
			foperate.optDate = date
			foperate.save(flush:true)
			if(params.check.equals("pass")) {
				opt = SCFIREConstants.PROJECT_APPROVE_PASS
			} else if(params.check.equals("refuse")) {
				opt = SCFIREConstants.PROJECT_APPROVE_REFUSE
			}
			
		}catch(Exception e){
		LOG.error("save project approve catch exception. "+e.getMessage())
	}
		redirect(action:"projectApprove",params: [opt:opt,projectid:projectid])
	}
	
	/**
	 * 款项支付审核结果处理
	 * @param status
	 * @return null
	 *
	 * **/
	def projectPayoffApprove() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		Member member = (Member)user
		//获取项目
		def projectid = params.projectid
		def project = null
		if(!params.payoffDate&&!params.money&&!params.OA) {
			redirect(action:"projectApproveStatus",params: [status:"wait"])
			return
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd")
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			if(!(project.verified =="execute" || project.verified =="expired"|| project.verified =="doing")){
				notFound()
				return
			}
			if(!(project.verified =="doing")){
				def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
				DBCollection projectCollection = db.getCollection("project")
				DBObject queryCondition= new BasicDBObject()
				queryCondition.put("_id",project.id)
				BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("verified", "doing")
					.append("apliNum", 0)
					)
				projectCollection.update(queryCondition, updateParameter,true,true)				
			}
			//操作记录
			Date date = new Date()
			def foperate = new FOperate()
			foperate.operate = "payoff"
			foperate.oa = params.OA
			foperate.optDate = date
			String s =params.money
			BigDecimal bd=new BigDecimal(s);
			bd=bd*100
			foperate.money =bd.intValue()
			foperate.payoffDate = df.parse(params.payoffDate)
			foperate.project = project
			foperate.mark = params.mark
			foperate.save(flush:true)
			
			//支付流水
			Payment payment= new Payment()
			payment.oa=params.OA
			payment.date = df.parse(params.payoffDate)
			payment.payMoney=bd.intValue()
			payment.remark = params.mark
			payment.project = project.id
			payment.member=member.id
			payment.save(flush:true)
			    DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd H:mm");
				List<String> list = new ArrayList<String>();
				feedBackService.insertFeedBacks("善款 "+payment.payMoney/100+"元 已于 "+df.format(payment.date)+" 支付，预计1-2个工作日后到账，欢迎大家持续关注项目后续的执行进展。", project.id+"",project.member,list ,"payMoney")
			
		}catch(Exception e){
		LOG.error("save project approve catch exception. "+e.getMessage())
	}
		redirect(action:"projectApproveStatus",params: [status:"wait"])
	}
	
	/**
	 * 项目退款审核管理
	 * @param status
	 * @return null
	 *
	 * **/
	def projectRefund() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取项目
		def projectid = params.projectid
		def project = null

		if(!params.excuse) {
			redirect(action:"projectApproveStatus",params: [status:"wait"])
			return
		}
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			Date date = new Date()
			def foperate = new FOperate()
			foperate.operate = "refund"
			foperate.excuse = params.excuse
			foperate.optDate = date
			foperate.project = project
			foperate.save(flush:true)
			
		}catch(Exception e){
		LOG.error("save project approve catch exception. "+e.getMessage())
	}
		redirect(action:"projectApproveStatus",params: [status:"wait"])
	}
	
	/**
	 * 结项审核管理
	 * @param status
	 * @return null
	 *
	 * **/
	@Transactional(propagation = Propagation.REQUIRED)
	def projectOverApprove() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取项目
		def projectid = params.projectid
		def flag = params.flag
		def project = null
		if(!params.check) {
			redirect(action:"projectApproveStatus",params: [status:"wait"])
			return
		}
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			Date date = new Date()
			def foperate = new FOperate()
			foperate.operate = "over"
			foperate.result = params.check
			def projectClosing = ProjectClosing.findByProject(project.id)
			if(projectClosing==null){
				notFound()
				return
			}
			if(params.check=="pass"){
				println params.check
				projectClosing.verified="pass"
				project.verified="over"
				def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
				DBCollection projectCollection = db.getCollection("project")
				DBObject queryCondition= new BasicDBObject()
				queryCondition.put("_id",project.id)
				BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("verified", "over"))
				projectCollection.update(queryCondition, updateParameter,true,true)
			}
			if(params.check=="refuse"){
				projectClosing.verified="refuse"
			}
			String s;
			if(params.excuse&&!params.excuse.equals("理由")) {
				foperate.excuse = params.excuse
				s=params.excuse
			}
			//project.save(flush:true)
			foperate.optDate = date
			foperate.project = project
			projectClosing.save(flush:true)
			foperate.save(flush:true)
			DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd H:mm");
			List<String> summaryImgs = projectClosing.summaryImgs
			if(params.check=="pass"){
					feedBackService.insertFeedBacks(SCFIREConstants.PROJECT_FEEDBACK_PASS_F+project.name+"”已于"+fmt.format(date)+"结项通过！", project.id+"",project.member,projectClosing.summaryImgs.subList(0,4),"closeProject")
			}
			def projectMember= Member.findById(project.member)
			
			if(params.check=="pass"){
				if(s==null){
					s="审批通过！"
				}
				if(flag=="pass"){
					weiXinService.template_status(WeiXinConstants.service_id, projectMember.openid, "亲爱的"+projectMember.nickname+",您提交的项目《"+project.name+"》,结项审核通过!", fmt.format(date), "项目结项", "申请结项", s , WeiXinConstants.server+"/project/createProjectCloseing?projectid="+project?.id)
				}
				SystemMessageService.sendSysMessage(SCFIREConstants.SYSTEM_MESSAGE_PROJECT_FUND_SUCCESS_FRONT+project.name+SCFIREConstants.SYSTEM_MESSAGE_PROJECT_FUND_SUCCESS_BACK, project.member);
				
				//结项成功：推送该项目所有捐赠人，提示用户项目结项成功，已进入执行阶段，点击详情持续关注项目进展
				Map<String, String> donateUsersOpenid = new HashMap<String, String>()
				
			def Criteriaproject = Donate.createCriteria()
			def dfc = {
				eq("project",project.id)
				order("date", "desc")
				projections {
					distinct ("member")
					   }
			}
			def members = Criteriaproject.listDistinct(dfc);
			for(Member member:members){
				donateUsersOpenid.put(member?.openid ,member?.openid)
			}
			println donateUsersOpenid.size()
				String s1 
				if(projectClosing.summary.length()>=50){
					s1=projectClosing.summary.substring(0, 50)+"..."
				}else{
				s1=projectClosing.summary
				}
				
				Map<String,Object> toMessage = new HashMap<String, Object>();
				toMessage.put("donateUsersOpenid",donateUsersOpenid);
				toMessage.put("detail","亲爱的"+projectMember.nickname+",您支持的"+project?.name+"项目已顺利结项，您的善款已经有力的帮助到真正有需要的人，赞一个！");
				toMessage.put("date",fmt.format(date));
				toMessage.put("ClosingDetail",s1);
				toMessage.put("url",WeiXinConstants.server+"/project/createProjectCloseing?projectid="+project?.id);
				new Thread(new SendMessageThred(toMessage)).start();
				
				
				
				//weiXinService.sendMassTemplateStatus(WeiXinConstants.service_id, donateUsersOpenid, "亲爱的"+project.member.nickname+",您支持的"+project?.name+"项目已顺利结项，您的善款已经有力的帮助到真正有需要的人，赞一个！", fmt.format(date), "结项报告", "成功", s1, WeiXinConstants.server+"/project/createProjectCloseing?projectid="+project?.id)
			}
			if(params.check=="refuse"){
				if(s==null){
					s="审批驳回！"
				}
				if(flag=="pass"){
				weiXinService.template_status(WeiXinConstants.service_id, projectMember.openid, "亲爱的"+projectMember.nickname+"您提交的项目《"+project.name+"》,审核被驳回", fmt.format(date), "项目结项", "申请结项", s , WeiXinConstants.server+"/project/createProjectCloseing?projectid="+project?.id)
				}
			}
			
		}catch(Exception e){
		LOG.error("save project approve catch exception. "+e.getMessage())
	}
		redirect(action:"projectApproveStatus",params: [status:"wait"])
	}
	/**
	 * 项目激活管理
	 * @param status
	 * @return null
	 *
	 * **/
	def projectActive() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取项目
		def projectid = params.projectid
		def project = null
		if(!params.duration||params.duration.equals("激活天数（1-99天）")) {
			//redirect(action:"projectApproveStatus",params: [status:"wait"])
			notFound()
			return
		}
		
		def duration = Integer.parseInt(params.duration)
		Date endDate = null
		try{
			
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			project = (Project)project
//			时间延期
			endDate = project.endDate
			Calendar calendar = Calendar.getInstance()
			calendar.setTime(endDate)
			calendar.add(Calendar.DAY_OF_WEEK, duration)
			endDate = calendar.getTime()
			
			Date date = new Date()
			def foperate = new FOperate()
			foperate.operate = "active"
			foperate.duration = duration
			foperate.optDate = date
			project.endDate = endDate
			if(endDate.getTime()>new Date().getTime()){
				if(project.verified =="execute" || project.verified =="expired")
				project.verified="pass"
			}
			foperate.project = project
			def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
			DBCollection projectCollection = db.getCollection("project")
			DBObject queryCondition= new BasicDBObject()
			queryCondition.put("_id",Integer.valueOf(projectid))
			BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("endDate", project.endDate)
				.append("verified", project.verified)
				.append("apliNum", 0)
				)
			
			projectCollection.update(queryCondition, updateParameter,true,true)
			foperate.save(flush:true)
		}catch(Exception e){
		LOG.error("save project approve catch exception. "+e.getMessage())
	}
		redirect(action:"projectApproveStatus",params: [status:"wait"])
	}
	
	/**
	 * 项目编辑管理
	 * @param status
	 * @return null
	 *
	 * **/
	def projectEdit() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取项目
		def projectid = params.projectid
		def project = null

		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
		}catch(Exception e){
			LOG.error("approve project catch exception. "+e.getMessage())
		}
		render view:"editProject",model:[user:user,roles:roles,project:project]
		
	}
	
	/**
	 * 项目编辑结果处理
	 * @param status
	 * @return null
	 *
	 * **/
	@Transactional(propagation = Propagation.REQUIRED)
	def dealProjectEdit() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取项目
		def projectid = params.projectid
		def project = null
		try{
			project = Project.findById(Long.valueOf(projectid))
			if (project == null) {
				notFound()
				return
			}
			
			project = (Project)project
			
			if(params.category) {
				def mainCate = MainCate.findByCode(params.category+"")
				project.mainCate=mainCate.id
			}
			if(params.title) {
				project.name = params.title
			}
			if(params.img) {
				project.img = params.img
			}
			if(params.description) {
				project.description = params.description
			}
			println params.content
			if(params.content) {
				project.detail = params.content	
			}
			if(params.preview) {
				
				projectreview(project);
				return 
			}
			if(params.submit) {
				project.save(flush:true)
				redirect  (controller: "project", action: "projectDetail",params: [user:user,roles:roles,projectid:projectid] )
				return
			}
		}catch(Exception e){
			LOG.error("deal project edit catch exception. "+e.getMessage())
			notFound()
			return
		}
		redirect(action:"projectApproveStatus",params: [status:SCFIREConstants.USER_APPROVE_WAIT])
	}
	
	
	def projectreview(Project projectinstence){	
		try {
		//项目捐赠人列表
		Set<Member> donates = new HashSet<Member>()
		println params.projectinstence
		Project project = projectinstence
		//一起捐和所有捐赠数（防止不必要的project中级联的donate加载）
		int donatesCount = 0;
		int subprjCount = 0;
		//剩余天数
		def lastDate = null
			def criteriaDonate = Donate.createCriteria()
			def filterDonate ={
				eq('project', project.id)
				maxResults(30)
			}
			def fDonates = criteriaDonate.list(filterDonate)
			Date curDate = new Date()
			if(curDate>=project.endDate){
				lastDate = 0
			}else{
				lastDate = project.endDate - curDate
			}
			//捐赠人信息去重
			if(fDonates!=null){
				//最多查询前10个
				for(Donate d:fDonates){
					Member m = Member.findById(d.member)
					//donates.add(d.member)
					donates.add(m)
					if(donates.size()>10){
						break
					}
				}
			}
			
			def fRuler = FRuler.findByProject(project)
			def subProjectSize = SubProject.countByProject(project.id)
			def member= Member.findById(project.member)
			def fundraises =Fundraise.findAllByProject(project.id)
		withFormat {
			html {
					render view: "projectdetailmb", model: [project:project,member:member,fundraises:fundraises,lastDate:lastDate,donates:donates, fRuler:fRuler,subProjectSize:subProjectSize]
			}
		}
		} catch (Exception e) {
		e.printStackTrace()
	}
	
		
		
	}
	
	def ProjectTotalDonate2(){
		try {
		String projectId = params.projectId
		if(projectId == null){
			notFound()
			return
		}
		
		Project project = Project.findById(projectId)
		if(project == null){
			notFound()
			return
		}
		def donates= Donate.findAllByProject(project.id)
		if(donates){
			project.donateNum=donates.size()
		}else{
		project.donateNum=0
		}
		println project.donateNum
		float f
		for(Donate d:donates){
			f+=d.donate_fee
		}
		def fdonates = FDonate.findAllByProject(project.id)
		for(FDonate d1:fdonates){
			f+=(d1.donate_fee*1.0/100)
		}
		if(fdonates){
			project.fDonateSize=fdonates.size()
		}else{
		project.fDonateSize=0
		}
		println project.fDonateSize
		def subProjects= SubProject.findAllByProject(project.id)
		if(subProjects){
			project.sbuProjectSize= subProjects.size()
		}else{
		project.sbuProjectSize= 0
		}
		println project.sbuProjectSize
		project.realAmount= f
		println project.realAmount
		
		project.rest = project.amount - project.realAmount
		if(project.rest<0){
			project.rest=0
		}
		def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
		DBCollection projectCollection = db.getCollection("project")
		DBObject queryCondition= new BasicDBObject()
		queryCondition.put("_id",Integer.valueOf(projectId))
		
		BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("donateNum", project.donateNum)
			.append("fDonateSize", project.fDonateSize)
			.append("sbuProjectSize", project.sbuProjectSize)
			.append("realAmount", project.realAmount)
			.append("rest", project.rest)
			.append("verified", project.verified)
			)
		
		projectCollection.update(queryCondition, updateParameter,true,true)
		} catch (Exception e) {
		e.printStackTrace()
	}
		
	}
	
	
	def sortAllDonateByMonth(){
		
		float total_money
		for(Donate d:doantes){
			total_money+=d.donate_fee
			println total_money
		}
		println total_money
	}
	
	def topDonate(){
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd")
		def beginDate
		if(params.beginDate==null){
			notFound()
			return
		}
		beginDate = df.parse(params.beginDate)
		def endDate
		if(params.endDate==null){
			notFound()
			return
		}
		endDate = df.parse(params.endDate)
		
		def doanteCreate = Donate.createCriteria()
		
		def	filterClosure = {
			ge("date",beginDate)
			lt("date",endDate)
			projections {
				distinct ("member")
				   }
		}
		def members = doanteCreate.listDistinct(filterClosure)	
		FileWriter   fw=new   FileWriter(new File("D:/topDonate2.txt"));
		BufferedWriter   bw=new   BufferedWriter(fw);
		int i=0
		for(Member user:members){
			i++
			def	filterClosure2 = {
				ge("date",beginDate)
				lt("date",endDate)
				eq("member",user.id)
				
			}
			
			def donates = doanteCreate.list(filterClosure2)
			if(donates){
				float totalMoney=0.0
				for(Donate d:donates){
					totalMoney+=d.donate_fee;
				}
				println user.id+"~"+donates.size()+"~"+totalMoney
				bw.write(user.id+"~"+donates.size()+"~"+totalMoney);
				bw.newLine();
				bw.flush();
				println i
			}
		}
		bw.close();
		fw.close();
	}
	
	
	def downDonateInfoReport(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd")
		def beginDate
		if(params.beginDate==null){
			notFound()
			return
		}
		beginDate = df.parse(params.beginDate)
		def endDate
		if(params.endDate==null){
			notFound()
			return
		}
		endDate = df.parse(params.endDate)
		
		def doanteCreate = Donate.createCriteria()
		
		def	filterClosure = {
			ge("date",beginDate)
			lt("date",endDate)
			eq("type","支付宝支付")
			
		}
		try{
			def donates = doanteCreate.list(filterClosure)
			List reports = new LinkedList<>()
			List fields = ["donateID", "userID", "nickname", "projectName", "verified" , "money" , "donate_fee" ,  "operate_fee" , 
				"operate_fee_status" ,"date","type","memberRaise","status","fundPool","FDonate_fee"]
			Map labels = ["donateID":"捐赠ID", "userID":"用户ID", "nickname":"昵称", "projectName":"项目名称", "verified":"项目状态" , "money":"总额" , "donate_fee":"捐赠金额 " ,  "operate_fee":"平台管理费" , 
				"operate_fee_status":"管理费" ,"date":"捐赠时间","type":"支付渠道","memberRaise":"一起捐发起人","status":"交易状态","fundPool":"配捐爱心池","FDonate_fee":"配捐金额"] 
			int i  = 0
			for(Donate donate:donates){
				i++
				def member =Member.findById(donate.member)
				def project= Project.findById(donate.project)
				DonateDetailReport report = new DonateDetailReport()
				report.donateID = donate.id
				report.userID = donate.member
				report.nickname = member?.nickname
				report.projectName = project.name
				report.verified =project.verified
				report.money = donate.money
				report.donate_fee = donate.donate_fee
				report.operate_fee = donate.operate_fee
				report.operate_fee_status = donate.operate_fee_status
				report.date = donate.date
				report.type = donate.type
				if(donate.subProject==null) {
					report.memberRaise = ""
				}else {
				def subProject = SubProject.findById(donate.subProject)
				def submember = Member.findById(subProject.member)
					report.memberRaise = submember?.nickname
				}
				report.status = donate.status
				if(donate.fDonate==null) {
					report.fundPool = ""
					report.FDonate_fee = ""
				} else {
					def fDonate  =FDonate.findById(donate.fDonate)
					def fundPool = FundPool.findById(fDonate.fundPool)
					report.fundPool = fundPool.name
					report.FDonate_fee = fDonate.donate_fee/100
				}
				reports.add(report)
				println i
			}
			
			
			//下载服务
			response.contentType = grailsApplication.config.grails.mime.types[params.exportType]
			response.setHeader("Content-disposition", "attachment;filename=Report"+params.beginDate+"__"+params.endDate+".${params.extension}")
			Map parameters = ["encoding":"UTF-8"]
			exportService.export(params.exportType, response.getOutputStream(), reports, fields, labels, null, parameters)
			return
		}catch(Exception e){
			LOG.error("down donate report catch exception. "+e.getMessage())
		}
		render "Export failure"
	}
	
	
	/*def SendMessage(){	
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
			String projectId = params.projectId
			if(projectId == null){
				notFound()
				return
			}
			Project project = Project.findById(Long.valueOf(projectId))
			if(project == null){
				notFound()
				return
			}
			
			Map<String, String> donateUsersOpenid = new HashMap<String, String>()
			Date  date = new Date();
			DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm");
			def Criteriaproject = Donate.createCriteria()
			def dfc = {
				eq("project",project.id)
				order("date", "desc")
				projections {
					distinct ("member")
					   }
			}
			def members = Criteriaproject.listDistinct(dfc);
			for(Member member:members){
				donateUsersOpenid.put(member?.openid , member?.nickname)
			}
			
			println donateUsersOpenid.size()
						
			weiXinService.sendMassTemplateStatus2(WeiXinConstants.service_id, donateUsersOpenid, "您好，感谢您支持“1起筑梦-筹大都会人寿梦想中心”项目； 线上众筹已到期截止，共获得80258人次爱心助力；点击详情关注最新进展！", fmt.format(date), "项目筹款", "筹款", "成功" , WeiXinConstants.server+"/project/projectDetail?projectid="+project?.id)
           println "asdfasdf"
	}*/
	
	
	
	
	def projectFeedbackManage(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		int offset = 0;
		params.max = 20;
		def projectid = params.projectid;
		if(projectid==null){
			notFound()
			return
		}
		
		String search = params.search
		String toflag = params.flag
		println toflag
		boolean flag
		if(toflag!=null&&toflag!="all"){
			try{
				flag = Boolean.valueOf(toflag).booleanValue();
			}catch(Exception e){
			   flag=true;
			}
		}
		def	filterClosure = {
			if(flag!=""&&flag!=null){
				if(flag==true){
					or{
						isNull("display_flag")
						eq("display_flag",true)
					}
				}else if(flag==false){
				eq("display_flag",false)
				}
			}
			if(search!=""&&search!=null){
				like("text","%"+search+"%")
			}
			eq("project",Long.valueOf(projectid))
			order("date", "desc")
		}
		def feedBackCreate = ProjectFeedback.createCriteria()
		def feedBacks = feedBackCreate.list(params,filterClosure)
		def totalCount = feedBackCreate.count(filterClosure)
		JSONArray feedbacjson = new JSONArray()
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		for(ProjectFeedback f:feedBacks){
			def project = Project.findById(f.project)
			JSONObject json = new JSONObject()
			json.put("id", f.id)
			json.put("projectName", project.name)
			json.put("text", f.text)
			json.put("date", sdf.format(f.date).substring(5))
			if(project.member ==f.member){
				json.put("del", true)
			}else{
			json.put("del", false)
			}
			if(f?.display_flag==null || true==f?.display_flag){
				json.put("show", true)
			}else{
				json.put("show", false)
			}
			feedbacjson.add(json)
		}	
		if(search=="null"){
			search=""
		}
		if(toflag=="null"){
			toflag=""
		}
		withFormat {
			html {
					render view: "feedBackManage", model: [projectid:projectid,user:user,roles:roles,feedbacjson:feedbacjson,search:search,flag:toflag,totalCount:totalCount]
			}
		}
	}
	
	def feedbackShow(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		String feedbackid = params.feedBackid
		String show = params.show
		if(feedbackid==null){
			notFound()
			return
		}
		if(show==null){
			notFound()
			return
		}
		def flag
			try{
				flag = Boolean.valueOf(show).booleanValue();
			}catch(Exception e){
			   flag=true;
			}
			
			def feedBack = ProjectFeedback.findById(Long.valueOf(feedbackid))	
			if(feedBack){
				feedBack.display_flag=flag;
				feedBack.save(flush:true)
			}
			redirect(action:"projectFeedbackManage",params: [projectid:feedBack.project])

	}
	
	
	
	def commentManage(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		int offset = 0;
		params.max = 20;
		def projectid = params.projectid;
		if(projectid==null){
			notFound()
			return
		}
		String search = params.search
		String toflag = params.flag
		println toflag
		boolean flag
		if(toflag!=null&&toflag!="all"&&toflag!="null"){
			try{
				flag = Boolean.valueOf(toflag).booleanValue();
			}catch(Exception e){
			   flag=true;
			}
		}
		def	filterClosure = {
			if(flag!=""&&flag!=null){
				if(flag==true){
					or{
						isNull("display_flag")
						eq("display_flag",true)
					}
				}else if(flag==false){
				eq("display_flag",false)
				}
			}
			if(search!=""&&search!=null&&search!="null"){
				like("text","%"+search+"%")
			}
			eq("project",Long.valueOf(projectid))
			order("date", "desc")
		}
		def commentCreate = Comment.createCriteria()
		def comments = commentCreate.list(params,filterClosure)
		def totalCount = commentCreate.count(filterClosure)
		JSONArray commentjson = new JSONArray()
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		for(Comment c:comments){
			def project = Project.findById(c.project)
			def member = Member.findById(c.member)
			JSONObject json = new JSONObject()
			json.put("id", c.id)
			json.put("projectName", project.name)
			json.put("memberName", member?.nickname)
			json.put("text", c.text)
			json.put("date", sdf.format(c.createDate).substring(5))
			if(c?.display_flag==null || true==c?.display_flag){
				json.put("show", true)
			}else{
				json.put("show", false)
			}
			commentjson.add(json)
		}	
		if(search=="null"){
			search=""
		}
		if(toflag=="null"){
			toflag=""
		}
		withFormat {
			html {
					render view: "commentManage", model: [projectid:projectid,user:user,roles:roles,commentjson:commentjson,search:search,flag:toflag,totalCount:totalCount]
			}
		}
	}
	
	
	def commentShow(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		String commentid = params.commentid
		String show = params.show
		if(commentid==null){
			notFound()
			return
		}
		if(show==null){
			notFound()
			return
		}
		def flag
			try{
				flag = Boolean.valueOf(show).booleanValue();
			}catch(Exception e){
			   flag=true;
			}
			
			def comment = Comment.findById(Long.valueOf(commentid))
			if(comment){
				comment.display_flag=flag;
				comment.save(flush:true)
			}
			redirect(action:"commentManage",params: [projectid:comment.project])
	}
	
	
	def privateKeyManage(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		int offset = 0;
		params.max = 20;
		String search = params.search
		String toflag = params.flag
		println toflag
		boolean flag
		if(toflag!=null&&toflag!="all"&&toflag!="null"){
			try{
				flag = Boolean.valueOf(toflag).booleanValue();
			}catch(Exception e){
			   flag=true;
			}
		}
		def	filterClosure = {
			if(flag!=""&&flag!=null){
				if(flag==true){
					or{
						eq("flag",true)
					}
				}else if(flag==false){
				eq("flag",false)
				}
			}
			if(search!=""&&search!=null&&search!="null"){
				or{
					like("sercurity_key","%"+search+"%")
					like("public_key","%"+search+"%")
				}
			}
			order("date", "desc")
		}
		def interfaceCreate = InterfaceMesage.createCriteria()
		def interfaceMesages= interfaceCreate.list(params,filterClosure)
		def totalCount = interfaceCreate.count(filterClosure)
		JSONArray commentjson = new JSONArray()
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		for(InterfaceMesage i:interfaceMesages){
			JSONObject json = new JSONObject()
			json.put("id", i.id)
			json.put("sercurity_key", i.sercurity_key)
			json.put("public_key", i.public_key)
			json.put("mark", i.mark);
			json.put("date", sdf.format(i.date).substring(5))
			if(i?.flag==null || true==i?.flag){
				json.put("show", true)
			}else{
				json.put("show", false)
			}
			commentjson.add(json)
		}
		if(search=="null"){
			search=""
		}
		if(toflag=="null"){
			toflag=""
		}
		withFormat {
			html {
					render view: "privateKeyManage", model: [user:user,roles:roles,commentjson:commentjson,search:search,flag:toflag,totalCount:totalCount]
			}
		}
	}
	
	
	def privateKeyShow(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		String key_id = params.key_id
		String show = params.show
		if(key_id==null){
			notFound()
			return
		}
		if(show==null){
			notFound()
			return
		}
		def flag
			try{
				flag = Boolean.valueOf(show).booleanValue();
			}catch(Exception e){
			   flag=true;
			}
			
			def interfaceMesage = InterfaceMesage.findById(Long.valueOf(key_id))
			if(interfaceMesage){
				interfaceMesage.flag=flag;
				interfaceMesage.save(flush:true)
			}
			redirect(action:"privateKeyManage",params: [])
	}
	
	def createPrivateKey(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		InterfaceMesage interfaceMesage = new InterfaceMesage();
		
		String sercurity_key =RandomUtil.generateLowerString(18)
		String public_key =RandomUtil.generateLowerString(18)
		
		
		interfaceMesage.mark=params.mark;
		
		interfaceMesage.sercurity_key =sercurity_key;
		interfaceMesage.public_key =public_key;
		interfaceMesage.date =new Date();
		interfaceMesage.update =new Date();
		interfaceMesage.save(flush:true);
		withFormat {
			html {
					redirect view: "privateKeyManage", model: []
			}
		}
		
	}
	
	
	
	
	
}
